package com.alibaba.citrus.ots.unified.inventory.facade.service;

import com.alibaba.citrus.ots.common.annotation.EpochTransactional;
import com.alibaba.citrus.ots.common.annotation.FacadeInvoker;
import com.alibaba.citrus.ots.common.exception.FacadeException;
import com.alibaba.citrus.ots.common.lock.RedisLock;
import com.alibaba.citrus.ots.common.log.ModuleEnum;
import com.alibaba.citrus.ots.common.util.DateUtils;
import com.alibaba.citrus.ots.common.util.TimeUtil;
import com.alibaba.citrus.ots.unified.inventory.functions.allocateApplyOrder.AllocateApplyOrderEntity;
import com.alibaba.citrus.ots.unified.inventory.functions.allocateApplyOrder.AllocateApplyOrderFactory;
import com.alibaba.citrus.ots.unified.inventory.repository.AllocateApplyOrderDetailReadRepository;
import com.alibaba.citrus.ots.unified.inventory.repository.AllocateApplyOrderDetailWriteRepository;
import com.alibaba.citrus.ots.unified.inventory.repository.AllocateApplyOrderReadRepository;
import com.alibaba.citrus.ots.unified.inventory.repository.AllocateApplyOrderWriteRepository;
import com.alibaba.citrus.ots.unified.inventory.utils.InfoUtil;
import com.alibaba.citrus.ots.unified.inventory.utils.OtsDateUtils;
import com.alibaba.cz.base.model.promotion.util.DateUtil;
import com.alibaba.cz.base.tool.log.model.OpLogModel;
import com.alibaba.cz.base.tool.log.model.OperatorType;
import com.alibaba.cz.base.tool.message.ErrorMessage;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.middleware.mq.runtime.EpochMessageService;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.alibaba.lattice2.epoch.user.dto.LoginUser;
import com.alibaba.lattice2.epoch.user.service.EpochLoginUserService;
import com.epoch.app.bcots.contants.BcOtsConstants;
import com.epoch.app.bcots.model.dto.BaselineGetOrganizationById2Request;
import com.epoch.app.bcots.model.dto.BatchQueryWarehouseByIdsRequest;
import com.epoch.app.bcots.model.dto.GetLoginEmployeeInfoResponse;
import com.epoch.app.bcots.model.dto.GetScItemGroupSelectResponse;
import com.epoch.app.bcots.model.dto.OrganizationSDO;
import com.epoch.app.bcots.model.dto.PageQueryPlanScItemListRequest;
import com.epoch.app.bcots.model.dto.PageQueryPlanScItemListResponse;
import com.epoch.app.bcots.model.dto.QueryCargoZoneByIdRequest;
import com.epoch.app.bcots.model.dto.QueryCargoZoneByIdResponse;
import com.epoch.app.bcots.model.dto.QueryGoodsListUnifiedInventoryRequest;
import com.epoch.app.bcots.model.dto.QueryGoodsListUnifiedInventoryResponse;
import com.epoch.app.bcots.model.dto.RoleSDO;
import com.epoch.app.bcots.model.dto.ScItemSDO;
import com.epoch.app.bcots.model.dto.SearchCargoZoneListRequest;
import com.epoch.app.bcots.model.dto.SearchCargoZoneListResponse;
import com.epoch.app.bcots.model.dto.SearchScItemRequest;
import com.epoch.app.bcots.model.dto.WarehouseInfo;
import com.epoch.app.bcots.model.dto.WmsQueryWarehouseZoneListRequest;
import com.epoch.app.bcots.model.dto.WmsQueryWarehouseZoneListResponse;
import com.epoch.app.bcots.service.BaseDataService;
import com.epoch.app.bcots.service.BcOtsService;
import com.epoch.app.bcots.service.PlatformEnhanceService;
import com.epoch.app.bcots.service.SalesPlanService;
import com.epoch.app.bcots.service.UnifiedInventoryService;
import com.epoch.app.otsplatformenhance.api.customeraddressquery.service.CustomerAddressQueryService;
import com.epoch.app.otsplatformenhance.domain.customeraddress.dto.BatchQueryByIdsRequest;
import com.epoch.app.otsplatformenhance.domain.customeraddress.model.CustomerAddress;
import com.epoch.app.otsplatformenhance.domain.customeraddress.service.CustomerAddressService;
import com.epoch.app.otsplatformenhance.service.OtsPlatformEnhanceService;
import com.epoch.app.otsunifiedinventory.api.allocateapplyorderdropdownselection.dto.QueryBranchCustomersRequest;
import com.epoch.app.otsunifiedinventory.api.allocateapplyorderdropdownselection.service.AllocateApplyOrderDropDownSelectionService;
import com.epoch.app.otsunifiedinventory.api.allocateapplyorderread.service.AllocateApplyOrderReadService;
import com.epoch.app.otsunifiedinventory.api.allocateapplyorderwrite.service.AllocateApplyOrderWriteService;
import com.epoch.app.otsunifiedinventory.api.allocateorderwrite.service.AllocateOrderWriteService;
import com.epoch.app.otsunifiedinventory.api.forecastwarehouse.dto.QueryDeliveryWarehouseByTypeRequest;
import com.epoch.app.otsunifiedinventory.api.forecastwarehouse.dto.QueryReceivingWarehouseByTypeRequest;
import com.epoch.app.otsunifiedinventory.api.forecastwarehouse.service.ForecastWarehouseService;
import com.epoch.app.otsunifiedinventory.contants.OtsUnifiedInventoryConstants;
import com.epoch.app.otsunifiedinventory.domain.allocateapplyorder.dto.AllocateApplyOrderLoadListRequest;
import com.epoch.app.otsunifiedinventory.domain.allocateapplyorder.dto.QueryListByIdsRequest;
import com.epoch.app.otsunifiedinventory.domain.allocateapplyorder.model.AllocateApplyOrder;
import com.epoch.app.otsunifiedinventory.domain.allocateapplyorder.service.AllocateApplyOrderService;
import com.epoch.app.otsunifiedinventory.domain.allocateorder.dto.LoadAllocateOrderRequest;
import com.epoch.app.otsunifiedinventory.domain.allocateorder.model.AllocateOrder;
import com.epoch.app.otsunifiedinventory.domain.allocateorder.service.AllocateOrderService;
import com.epoch.app.otsunifiedinventory.dto.request.CancelAllocateApplyOrderRequest;
import com.epoch.app.otsunifiedinventory.dto.request.CopyAllocateApplyOrderRequest;
import com.epoch.app.otsunifiedinventory.dto.request.QueryAllocateApplyOrderRequest;
import com.epoch.app.otsunifiedinventory.dto.request.RejectAllocateApplyOrderRequest;
import com.epoch.app.otsunifiedinventory.dto.response.AllocateApplyOrderDetailDTO;
import com.epoch.app.otsunifiedinventory.dto.response.AllocateApplyOrderGoodsDetailDTO;
import com.epoch.app.otsunifiedinventory.dto.response.AllocateApplyOrderResponse;
import com.epoch.app.otsunifiedinventory.dto.response.AllocateOrderCreateResponse;
import com.epoch.app.otsunifiedinventory.dto.response.AllocateOrderDetailBatchGetScItemResponse;
import com.epoch.app.otsunifiedinventory.dto.response.DeliveryWarehouseChoiceDTO;
import com.epoch.app.otsunifiedinventory.model.dto.AllocateApplyOrderBatchSubmitRequest;
import com.epoch.app.otsunifiedinventory.model.dto.AllocateApplyOrderBatchSubmitResponse;
import com.epoch.app.otsunifiedinventory.model.dto.AllocateApplyOrderCreateDTO;
import com.epoch.app.otsunifiedinventory.model.dto.AllocateApplyOrderDetailCreateDTO;
import com.epoch.app.otsunifiedinventory.model.dto.AllocateApplyOrderImportListRequest;
import com.epoch.app.otsunifiedinventory.model.dto.AllocateApplyOrderImportRequest;
import com.epoch.app.otsunifiedinventory.model.dto.AllocateApplyOrderQueryGoodsListDateilResponse;
import com.epoch.app.otsunifiedinventory.model.dto.AllocateApplyOrderQueryGoodsListResponse;
import com.epoch.app.otsunifiedinventory.model.dto.AllocateApplyOrderReplyDTO;
import com.epoch.app.otsunifiedinventory.model.dto.AllocateApplyOrderUpdateDTO;
import com.epoch.app.otsunifiedinventory.model.dto.AllocateOrderCreateRequest;
import com.epoch.app.otsunifiedinventory.model.dto.AllocateOrderScItemDetailDTO;
import com.epoch.app.otsunifiedinventory.model.dto.ApplyOrderQueryGoodsListRequest;
import com.epoch.app.otsunifiedinventory.model.dto.BranchCustomersDTO;
import com.epoch.app.otsunifiedinventory.model.dto.QueryCustomerAddressDTO;
import com.epoch.app.otsunifiedinventory.model.dto.QueryCustomerAddressRequest;
import com.epoch.app.otsunifiedinventory.model.dto.SapCallbackAllocateApplyOrderEquest;
import com.epoch.app.otsunifiedinventory.model.dto.WmsSDO;
import com.epoch.app.otsunifiedinventory.model.enums.AllocateApplyOrderOperationTypeEnum;
import com.epoch.app.otsunifiedinventory.model.enums.AllocateOrderType;
import com.epoch.app.otsunifiedinventory.sdo.enums.*;
import com.google.common.collect.Lists;
import lombok.Data;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Comparator;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author zhangguoqing
 * @date 2021/08/25
 */
@Component
@Primary
public class AllocateApplyOrderWriteServiceImpl implements AllocateApplyOrderWriteService {

    private static final String orderTime = "16:00:00";
    private static final String HEADQUARTERS_SALES_ALLOCATION_ORDER_TIME = "09:30:00";
    private final static String FOUR_STRING = "4";
    private final static Integer PLAN_TYPE = 1;
    private final static String YES = "1";
    //总部内部售达方编号
    private final static String SAP_INTERNAL_SALES_BP_CODE = "sapInternalSalesBPCode";
    //总部内部送达方编号
    private final static String SAP_INTERNAL_DELIVERY_BP_CODE = "sapInternalDeliveryBPCode";
    //总部售达方编号
    private final static String SAP_SALE_BP_CODE = "sapSaleBPCode";
    //总部送达方编号
    private final static String SAP_DELIVERY_BP_CODE = "sapDeliveryBPCode";
    /**
     * 空字符串
     */
    private static final String NULL_STRING = "";
    private static final String MONTH_COUNT = "monthCount";
    private static final String SCITEM_NAME = "scItemName";
    private static final String SCITEM_ID = "scItemId";
    private static final String SCITEM_IDS = "scItemIds";
    private static final String TYPE_STRING = "type";
    private static final String CODE = "code";
    private static final String STATUS = "status";

    private static final String OUTER_ID = "outerId";

    private static final String MONTH_FIRST_COUNT = "monthFirstCount";
    private static final String MONTH_MIDDLE_COUNT = "monthMiddleCount";
    private static final String MONTH_LAST_COUNT = "monthLastCount";
    private static final String ONE_STRING = "1";
    private static final String TWO_STRING = "2";
    private static final String THREE_STRING = "3";
    private static final String TWENTY_STRING = "20";
    private static final String NINETY_STRING = "90";
    private static final String STRING_ONE = "01";

    private static final String ORG_SALES_ORGANIZATION_CODE = "6000";
    private static final String DATE_FORMAT = "yyyy-MM-dd";
    private static final String ELEVEN_STRING = "11";
    private static final String WAREHOUSE_FACTORY_TYPE = "5";
    private static final String WAREHOUSE_SHARED_TYPE = "2";
    private static final String ALLOCATE_APPLY_ORDER_DETAIL = "allocateApplyOrderDetail";

    //分子公司业务员
    private static final String SALES_MAN_ROLE_CODE = "001";

    com.alibaba.cz.base.tool.log.Log log = com.alibaba.cz.base.tool.log.Log.getLogger(AllocateApplyOrderWriteServiceImpl.class);
    @Resource
    private AllocateApplyOrderWriteRepository allocateApplyOrderWriteRepository;

    @Resource
    private AllocateOrderService allocateOrderService;

    @Resource
    private PlatformEnhanceService platformEnhanceService;

    @Resource
    private AllocateApplyOrderDetailWriteRepository allocateApplyOrderDetailWriteRepository;

    @Resource
    @Qualifier("allocateApplyOrderReadServiceImpl")
    private AllocateApplyOrderReadService allocateApplyOrderReadService;

    @Resource
    private AllocateApplyOrderReadRepository allocateApplyOrderReadRepository;

    @Resource
    private AllocateApplyOrderDetailReadRepository allocateApplyOrderDetailReadRepository;

    @Resource
    @Qualifier("allocateOrderWriteServiceImpl")
    private AllocateOrderWriteService allocateOrderWriteService;

    @Resource
    private SalesPlanService salesPlanService;

    @Resource
    private EpochMessageService messageService;

    @Resource
    private UnifiedInventoryService unifiedInventoryService;
    @Resource
    BcOtsService bcOtsService;
    @Resource
    private BaseDataService baseDataService;

    @Resource
    private CustomerAddressQueryService customerAddressQueryService;

    @Resource
    private AllocateApplyOrderGoodsServiceImpl allocateApplyOrderGoodsService;

    @Resource
    private EpochLoginUserService epochLoginUserService;

    @Resource
    private AllocateApplyOrderDropDownSelectionService allocateApplyOrderDropDownSelectionService;

    @Resource
    private CustomerAddressService customerAddressService;

    @Resource
    private ForecastWarehouseService forecastWarehouseService;

    @Resource
    private AllocateApplyOrderWriteServiceImpl allocateApplyOrderWriteServiceImpl;
    @Resource
    private AllocateApplyOrderService allocateApplyOrderService;

    @Resource
    private OtsPlatformEnhanceService otsPlatformEnhanceService;

    @Override
    @FacadeInvoker(value = "创建调拨预报主单", errorCode = "OTS-03-001-00-15-026")
    public Result<AllocateApplyOrderDetailDTO> createAllocateApplyOrder(
            AllocateApplyOrderCreateDTO allocateApplyOrderCreateDTO) {
        log.info("AllocateApplyOrderWriteServiceImpl.createAllocateApplyOrder,request:{}", JSON.toJSONString(allocateApplyOrderCreateDTO));
        if (Objects.nonNull(allocateApplyOrderCreateDTO.getIsDTC())&&allocateApplyOrderCreateDTO.getIsDTC()&&!DocumentTypeEnum.HEADQUARTERS_SALES_ALLOCATION.getCode().equals(allocateApplyOrderCreateDTO.getType().toString())) {
            throw new FacadeException("OTS-03-001-00-15-087");
        }
        //判断前端是否传总部渠道编码，传了取前端传的，没传给默认值，类型等于总部销售调拨给20，其余给90
        if (Objects.nonNull(allocateApplyOrderCreateDTO.getHeadquartersChannelCode())) {
            //校验渠道编码是不是正确
            if (TWENTY_STRING.equals(allocateApplyOrderCreateDTO.getHeadquartersChannelCode())||NINETY_STRING.equals(allocateApplyOrderCreateDTO.getHeadquartersChannelCode())){
                allocateApplyOrderCreateDTO.setHeadquartersChannelCode(allocateApplyOrderCreateDTO.getHeadquartersChannelCode());
            }else {
                throw new FacadeException("OTS-03-001-00-15-088");
            }
        } else {
            //总部销售调拨 20 计划调拨 90
            if (DocumentTypeEnum.HEADQUARTERS_SALES_ALLOCATION.getCode().equals(allocateApplyOrderCreateDTO.getType().toString())) {
                allocateApplyOrderCreateDTO.setHeadquartersChannelCode(TWENTY_STRING);
            } else {
                allocateApplyOrderCreateDTO.setHeadquartersChannelCode(NINETY_STRING);
            }
        }
        allocateApplyOrderCreateDTO.setHeadquartersOrganizationCode(Objects.nonNull(allocateApplyOrderCreateDTO.getHeadquartersOrganizationCode()) ? allocateApplyOrderCreateDTO.getHeadquartersOrganizationCode() : ORG_SALES_ORGANIZATION_CODE);
        Boolean isDTC = null == allocateApplyOrderCreateDTO.getIsDTC() ? false : true;
        //获取仓库信息
        Map<String, JSONObject> warehouseIdMap = new HashMap<>();
        //仓库id集合
        Set<String> warehouseIds = new HashSet<>();
        warehouseIds.add(allocateApplyOrderCreateDTO.getReceiveWarehouseId() == null?null:allocateApplyOrderCreateDTO.getReceiveWarehouseId().toString());
        warehouseIds.add(allocateApplyOrderCreateDTO.getShipWarehouseId());
        BatchQueryWarehouseByIdsRequest batchQueryWarehouseByIdsRequest = new BatchQueryWarehouseByIdsRequest();
        batchQueryWarehouseByIdsRequest.setWarehouseIds(new ArrayList(warehouseIds));
        batchQueryWarehouseByIdsRequest.setModelList(Lists.newArrayList(1, 3, 5));
        Object data = unifiedInventoryService.batchQueryWarehouseByIds(batchQueryWarehouseByIdsRequest);
        if (Objects.nonNull(data)) {
            JSONObject js = JSON.parseObject(JSON.toJSONString(data));
            if (Objects.nonNull(js)) {
                JSONArray array = js.getJSONArray("result");
                if (Objects.nonNull(array) && array.size() > 0) {
                    for (int i = 0; i < array.size(); i++) {
                        JSONObject object = array.getJSONObject(i);
                        if (Objects.nonNull(object)) {
                            warehouseIdMap.put(object.getString("id"), object);
                        }
                    }
                }
            }
        }
        //校验收发货仓编码 权限问题
        JSONObject receiveWarehouseCodeJson = warehouseIdMap.get(allocateApplyOrderCreateDTO.getReceiveWarehouseId()==null?null:allocateApplyOrderCreateDTO.getReceiveWarehouseId().toString());
        JSONObject shipWarehouseCodeJson = warehouseIdMap.get(allocateApplyOrderCreateDTO.getShipWarehouseId());

        String receiveWarehouseCode = null;
        String shipWarehouseCode = null;
        if (Objects.nonNull(receiveWarehouseCodeJson)) {
            receiveWarehouseCode = receiveWarehouseCodeJson.getString("code");
        }
        if (Objects.nonNull(shipWarehouseCodeJson)) {
            shipWarehouseCode = shipWarehouseCodeJson.getString("code");
        }
        WarehouseBaseInfo warehouseInfo = checkWarehouse(receiveWarehouseCode, shipWarehouseCode, allocateApplyOrderCreateDTO.getType(), isDTC ? 1 : 0);

        if (!isDTC) {
            if (Objects.isNull(warehouseInfo) || StringUtils.isEmpty(warehouseInfo.getReceiveWarehouseId())) {
                throw new FacadeException("OTS-03-001-00-15-076");
            }
        }
        if (Objects.isNull(warehouseInfo) || StringUtils.isEmpty(warehouseInfo.getDeliveryWarehouseId())) {
            throw new FacadeException("OTS-03-001-00-15-077");
        }

        /**
         * 判断收发货仓类型是否正确
         */
        //获取收货仓档案信息
        if (Objects.nonNull(allocateApplyOrderCreateDTO.getReceiveWarehouseId())) {
            WmsSDO shipWmsSDO = InfoUtil.getWmsSDO(allocateApplyOrderCreateDTO.getReceiveWarehouseId().toString());
            if (Objects.nonNull(shipWmsSDO) && Objects.nonNull(shipWmsSDO.getWarehouseId())) {
                allocateApplyOrderCreateDTO.setReceiveCargoZoneId(Integer.valueOf(shipWmsSDO.getWarehouseId()));
                //收货仓不能是工厂类型仓库
                if (StringUtils.isNotEmpty(shipWmsSDO.getType()) && WAREHOUSE_FACTORY_TYPE.equals(shipWmsSDO.getType())) {
                    throw new FacadeException("OTS-03-001-00-15-053");
                }
            }
        }
        //获取发货仓档案信息
        if (Objects.nonNull(allocateApplyOrderCreateDTO.getShipWarehouseId())) {
            WmsSDO shipWmsSDO = InfoUtil.getWmsSDO(allocateApplyOrderCreateDTO.getShipWarehouseId().toString());
            if (Objects.nonNull(shipWmsSDO) && Objects.nonNull(shipWmsSDO.getWarehouseId())) {
                allocateApplyOrderCreateDTO.setShipCargoZoneId(shipWmsSDO.getWarehouseId());
                //判断调拨预报单类型，如果是计划 判断仓库是不是工厂类型，如果不是报错
                String shipWmsType = "";
                if (StringUtils.isNotEmpty(shipWmsSDO.getType())) {
                    String[] shipWmsTypes = shipWmsSDO.getType().split("\\.");
                    shipWmsType = shipWmsTypes[0];
                }
                if (DocumentTypeEnum.PLANNED_ALLOCATION.getCode().equals(allocateApplyOrderCreateDTO.getType().toString())) {
                    if (StringUtils.isNotEmpty(shipWmsSDO.getType()) && !WAREHOUSE_FACTORY_TYPE.equals(shipWmsType)) {
                        throw new FacadeException("OTS-03-001-00-15-054");
                    }
                }
                //判断调拨预报类型，如果是销售类型 判断仓库是不是是不是工厂和共享仓，如果不是就报错
                if (DocumentTypeEnum.HEADQUARTERS_SALES_ALLOCATION.getCode().equals(allocateApplyOrderCreateDTO.getType().toString())) {
                    if (StringUtils.isNotEmpty(shipWmsSDO.getType()) && !WAREHOUSE_FACTORY_TYPE.equals(shipWmsType)&&!WAREHOUSE_SHARED_TYPE.equals(shipWmsType)) {
                        throw new FacadeException("OTS-03-001-00-15-089");
                    }
                }
                //判断调拨预报单类型，如果是计划和总部销售类型 判断仓库是不是非工厂类型，如果不是报错
                if (DocumentTypeEnum.SAME_COMPANY_ALLOCATION.getCode().equals(allocateApplyOrderCreateDTO.getType().toString())
                        || DocumentTypeEnum.CROSS_COMPANY_BORROW_GOODS_ALLOCATION.getCode().equals(allocateApplyOrderCreateDTO.getType().toString())) {
                    if (StringUtils.isNotEmpty(shipWmsSDO.getType()) && WAREHOUSE_FACTORY_TYPE.equals(shipWmsType)) {
                        throw new FacadeException("OTS-03-001-00-15-055");
                    }
                }
            }
        }

        //地址信息
        if (Objects.nonNull(allocateApplyOrderCreateDTO.getCustomerAddressId())) {
            log.info("创建调拨预报单查询客户地址入参code：" + allocateApplyOrderCreateDTO.getCustomerAddressId());
            BatchQueryByIdsRequest batchQueryByIdsRequest = new BatchQueryByIdsRequest();
            batchQueryByIdsRequest.setIdList(Lists.newArrayList(allocateApplyOrderCreateDTO.getCustomerAddressId()));
            log.info("AllocateApplyOrderWriteServiceImpl.createAllocateApplyOrder.batchQueryByIds,request:{}", JSON.toJSONString(batchQueryByIdsRequest));
            Result<List<CustomerAddress>> listResult = customerAddressService.batchQueryByIds(batchQueryByIdsRequest);
            log.info("AllocateApplyOrderWriteServiceImpl.createAllocateApplyOrder.batchQueryByIds,result:{}", JSON.toJSONString(listResult));
            log.info("创建调拨预报单查询客户地址信息返回参：" + JSONObject.toJSONString(listResult));
            if (Objects.nonNull(listResult) && CollectionUtils.isNotEmpty(listResult.getResult())) {
                List<CustomerAddress> addressList = listResult.getResult();
                for (CustomerAddress customerAddress : addressList) {
                    allocateApplyOrderCreateDTO.setCustomer(customerAddress.getCustomerCode());
                    allocateApplyOrderCreateDTO.setCustomerAddress(customerAddress.getAddressCode());
                }
            } else {
                throw new FacadeException("OTS-03-001-00-15-075");
            }
        }
        //判断时间是否正确
        //单据日期
        if (Objects.nonNull(allocateApplyOrderCreateDTO.getOrderTime())){
            if (!isDateError(allocateApplyOrderCreateDTO.getOrderTime())){
                throw new FacadeException("OTS-03-001-00-15-080");
            }
        }
        //生效日期
        if (Objects.nonNull(allocateApplyOrderCreateDTO.getTakeEffectTime())){
            if (!isDateError(allocateApplyOrderCreateDTO.getTakeEffectTime())){
                throw new FacadeException("OTS-03-001-00-15-081");
            }
        }
        //生效至日期
        if (Objects.nonNull(allocateApplyOrderCreateDTO.getInvalidDate())){
            if (!isDateError(allocateApplyOrderCreateDTO.getInvalidDate())){
                throw new FacadeException("OTS-03-001-00-15-082");
            }
        }
        //插入调拨预报单
        log.info("AllocateApplyOrderWriteServiceImpl.createAllocateApplyOrder.create,request:{}", JSON.toJSONString(allocateApplyOrderCreateDTO));
        AllocateApplyOrderEntity allocateApplyOrderEntity = AllocateApplyOrderFactory.create(allocateApplyOrderCreateDTO);
        String code = allocateApplyOrderEntity.create();
        log.info("AllocateApplyOrderWriteServiceImpl.createAllocateApplyOrder.result,request:{}", code);

        //查询调拨预报单
        QueryAllocateApplyOrderRequest queryAllocateApplyOrderRequest = new QueryAllocateApplyOrderRequest();
        queryAllocateApplyOrderRequest.setCode(code);
        log.info("AllocateApplyOrderWriteServiceImpl.createAllocateApplyOrder.queryAllocateApplyOrderByCode,request:{}", code);
        Result<AllocateApplyOrderDetailDTO> allocateApplyOrderDetailDTOResult = allocateApplyOrderReadService.queryAllocateApplyOrderByCode(queryAllocateApplyOrderRequest);
        log.info("AllocateApplyOrderWriteServiceImpl.createAllocateApplyOrder.queryAllocateApplyOrderByCode,result:{}", allocateApplyOrderDetailDTOResult);
        //添加单据日志
        Map<String, String> features = new HashMap<>();
        features.put(CODE, code);
        features.put(STATUS, allocateApplyOrderDetailDTOResult.getResult().getStatus().toString());
        saveDocumentLog(new AllocateApplyOrderDetailDTO(), allocateApplyOrderDetailDTOResult.getResult(), Integer.valueOf(AllocateApplyOrderOperationTypeEnum.CREATE.getValue()), features);
        //判断月度计划是否有值，有值带出月度计划
        if (Objects.nonNull(allocateApplyOrderCreateDTO.getMonthPlan())) {
            log.info("AllocateApplyOrderWriteServiceImpl.createAllocateApplyOrder.queryAllocateApplyOrderGoodsDetailDTOByMonthPlan,request:{}", allocateApplyOrderCreateDTO);
            List<AllocateApplyOrderGoodsDetailDTO> allocateApplyOrderGoodsDetailDTOS = queryAllocateApplyOrderGoodsDetailDTOByMonthPlan(allocateApplyOrderCreateDTO);
            log.info("AllocateApplyOrderWriteServiceImpl.createAllocateApplyOrder.queryAllocateApplyOrderGoodsDetailDTOByMonthPlan,result:{}", allocateApplyOrderGoodsDetailDTOS);
            if (CollectionUtils.isNotEmpty(allocateApplyOrderGoodsDetailDTOS)) {
                allocateApplyOrderDetailDTOResult.getResult().setList(allocateApplyOrderGoodsDetailDTOS);
            }
        }
        log.info("AllocateApplyOrderWriteServiceImpl.createAllocateApplyOrder,result:{}", allocateApplyOrderDetailDTOResult);
        return allocateApplyOrderDetailDTOResult;
    }

    private boolean isDateError(Date date){
        if (Objects.nonNull(date)) {
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String sameDayDateString = dateFormat.format(new Date());
            Date sameDayDate = null;
            try {
                sameDayDate = dateFormat.parse(sameDayDateString);
            } catch (ParseException e) {
                return false;
            }

            if (date.getTime() >= sameDayDate.getTime()) {
                return true;
            }
        }
        return false;
    }


    private List<AllocateApplyOrderGoodsDetailDTO> queryAllocateApplyOrderGoodsDetailDTOByMonthPlan(AllocateApplyOrderCreateDTO allocateApplyOrderCreateDTO) {
        log.info("AllocateApplyOrderWriteServiceImpl.queryAllocateApplyOrderGoodsDetailDTOByMonthPlan,request:{}", JSON.toJSONString(allocateApplyOrderCreateDTO));
        PageQueryPlanScItemListRequest pageQueryPlanScItemListRequest = new PageQueryPlanScItemListRequest();
//            pageQueryPlanScItemListRequest.setPlanId(allocateApplyOrderCreateDTO.getMonthPlan());
        pageQueryPlanScItemListRequest.setPlanId(allocateApplyOrderCreateDTO.getMonthPlan());
        //维度类型 1：业务员提报 2：部门提报 3：渠道提报 4：组织提报 5：业务维度提报
        pageQueryPlanScItemListRequest.setBizType(104);
        pageQueryPlanScItemListRequest.setPoolType(2);
        //对应维度条件id  销售组织
        pageQueryPlanScItemListRequest.setBizId(allocateApplyOrderCreateDTO.getSalesOrganizationCode());
        //页码
        pageQueryPlanScItemListRequest.setPage(1);
        //大小
        pageQueryPlanScItemListRequest.setSize(999);
        log.info("AllocateApplyOrderWriteServiceImpl.queryAllocateApplyOrderGoodsDetailDTOByMonthPlan.pageQueryPlanScItemList,request:{}", JSON.toJSONString(pageQueryPlanScItemListRequest));
        PageQueryPlanScItemListResponse pageQueryPlanScItemListResponse = salesPlanService.pageQueryPlanScItemList(pageQueryPlanScItemListRequest);
        log.info("AllocateApplyOrderWriteServiceImpl.queryAllocateApplyOrderGoodsDetailDTOByMonthPlan.pageQueryPlanScItemList,result:{}", JSON.toJSONString(pageQueryPlanScItemListResponse));
        log.info("创建调拨预报单-查找月度计划入参销售组织：{}，返回对象：{}", pageQueryPlanScItemListRequest.getBizId(), JSONObject.toJSONString(pageQueryPlanScItemListResponse));

        if (Objects.nonNull(pageQueryPlanScItemListResponse) && Objects.nonNull(pageQueryPlanScItemListResponse.getResult())) {
            List<Map> resultMap = pageQueryPlanScItemListResponse.getResult();
            //获取物料编码
            SearchScItemRequest searchScItemRequest = new SearchScItemRequest();
            Map<String, List<String>> searchScItemScItemIdsMap = new HashMap<>();
            Set<String> scItemIdsSet = new HashSet<>();
            for (Map result : resultMap) {
                if (Objects.isNull(result.get(SCITEM_ID))) {
                    scItemIdsSet.add(result.get(SCITEM_ID).toString());
                }
            }
            searchScItemScItemIdsMap.put(SCITEM_IDS, new ArrayList<>(scItemIdsSet));
            searchScItemRequest.setSearchReqDTO(searchScItemScItemIdsMap);
            Result<List<ScItemSDO>> scItemSDOS = baseDataService.searchScItem(searchScItemRequest);
            Map<String, String> scItemSDOMap = new HashMap<>();
            if (Objects.nonNull(scItemSDOS) && Objects.nonNull(scItemSDOS.getResult())) {
                for (ScItemSDO scItemSDO : scItemSDOS.getResult()) {
                    scItemSDOMap.put(scItemSDO.getScItemId(), Objects.isNull(scItemSDO.getOuterId()) ? NULL_STRING : scItemSDO.getOuterId());
                }
            }
            Integer lineNo = 0;
            List<AllocateApplyOrderGoodsDetailDTO> allocateApplyOrderGoodsDetailDTOS = new ArrayList<>();
            //组装预报单子单数据
            for (Map result : resultMap) {
                AllocateApplyOrderGoodsDetailDTO allocateApplyOrderGoodsDetailDTO = new AllocateApplyOrderGoodsDetailDTO();
                allocateApplyOrderGoodsDetailDTO.setLineNo(++lineNo);
                //提报数量 ，根据选择上中下旬字段取不同的值
                if (Objects.nonNull(allocateApplyOrderCreateDTO.getTenDays())) {
                    //上
                    if (Objects.nonNull(result.get(MONTH_FIRST_COUNT)) && ONE_STRING.equals(allocateApplyOrderCreateDTO.getTenDays())) {
                        Double monthFirstCount = (Double) result.get(MONTH_FIRST_COUNT);
                        allocateApplyOrderGoodsDetailDTO.setApplyQuantity(monthFirstCount.intValue());
                    }
                    //中
                    if (Objects.nonNull(result.get(MONTH_MIDDLE_COUNT)) && TWO_STRING.equals(allocateApplyOrderCreateDTO.getTenDays())) {
                        Double monthFirstCount = (Double) result.get(MONTH_FIRST_COUNT);
                        Double monthMiddleCount = (Double) result.get(MONTH_MIDDLE_COUNT);
                        if (Objects.nonNull(monthFirstCount)) {
                            monthMiddleCount = monthFirstCount + monthMiddleCount;
                        }
                        allocateApplyOrderGoodsDetailDTO.setApplyQuantity(monthMiddleCount.intValue());
                    }
                    //下
                    if (Objects.nonNull(result.get(MONTH_LAST_COUNT)) && THREE_STRING.equals(allocateApplyOrderCreateDTO.getTenDays())) {
                        Double monthFirstCount = (Double) result.get(MONTH_FIRST_COUNT);
                        Double monthMiddleCount = (Double) result.get(MONTH_MIDDLE_COUNT);
                        Double monthLastCount = (Double) result.get(MONTH_LAST_COUNT);
                        if (Objects.nonNull(monthFirstCount)) {
                            monthLastCount = monthLastCount + monthFirstCount;
                        }
                        if (Objects.nonNull(monthMiddleCount)) {
                            monthLastCount = monthLastCount + monthMiddleCount;
                        }
                        allocateApplyOrderGoodsDetailDTO.setApplyQuantity(monthLastCount.intValue());
                    }
                } else {
                    //计划量
                    if (Objects.nonNull(result.get(MONTH_COUNT))) {
                        Double monthCount = (Double) result.get(MONTH_COUNT);
                        allocateApplyOrderGoodsDetailDTO.setApplyQuantity(monthCount.intValue());
                    }
                }
                //调拨预报单id
//                allocateApplyOrderGoodsDetailDTO.setAllocateApplyOrderId(allocateApplyOrderDetailDTOResult.getResult().getId().toString());
//                //需要查找 货品名称
                allocateApplyOrderGoodsDetailDTO.setTitle(Objects.isNull(result.get(SCITEM_NAME)) ? NULL_STRING : result.get(SCITEM_NAME).toString());
                //货品id
                allocateApplyOrderGoodsDetailDTO.setGoodsId(Objects.isNull(result.get(SCITEM_ID)) ? NULL_STRING : result.get(SCITEM_ID).toString());
                //货品编码
                allocateApplyOrderGoodsDetailDTO.setScItemId(Objects.isNull(result.get(OUTER_ID)) ? NULL_STRING : result.get(OUTER_ID).toString());
                allocateApplyOrderGoodsDetailDTOS.add(allocateApplyOrderGoodsDetailDTO);
            }
            log.info("AllocateApplyOrderWriteServiceImpl.queryAllocateApplyOrderGoodsDetailDTOByMonthPlan,result:{}", JSON.toJSONString(allocateApplyOrderGoodsDetailDTOS));
            return allocateApplyOrderGoodsDetailDTOS;
        }
        return null;
    }

    @Override
    @FacadeInvoker(value = "更新预调拨单", errorCode = "OTS-03-001-00-15-036")
    public Result<Boolean> updateAllocateApplyOrder(AllocateApplyOrderUpdateDTO allocateApplyOrderUpdateDTO) {
        log.info("AllocateApplyOrderWriteServiceImpl.updateAllocateApplyOrder,request:{}", JSON.toJSONString(allocateApplyOrderUpdateDTO));
        QueryAllocateApplyOrderRequest queryAllocateApplyOrderRequest = new QueryAllocateApplyOrderRequest();
        queryAllocateApplyOrderRequest.setCode(allocateApplyOrderUpdateDTO.getCode());
        log.info("AllocateApplyOrderWriteServiceImpl.updateAllocateApplyOrder.queryAllocateApplyOrderByCode,request:{}", JSON.toJSONString(queryAllocateApplyOrderRequest));
        Result<AllocateApplyOrderDetailDTO> allocateApplyOrderDetailDTOOld = allocateApplyOrderReadService.queryAllocateApplyOrderByCode(queryAllocateApplyOrderRequest);
        log.info("AllocateApplyOrderWriteServiceImpl.updateAllocateApplyOrder.queryAllocateApplyOrderByCode,allocateApplyOrderDetailDTOOldResult:{}", JSON.toJSONString(allocateApplyOrderDetailDTOOld));
        AllocateApplyOrderEntity allocateApplyOrderEntity;

//        try (RedisLock lock = new RedisLock(BcOtsConstants.REDIS_CACHE_CODE(), allocateApplyOrderUpdateDTO.getCode())) {
//            boolean locked = lock.lock();
//            if (!locked) {
//                log.error("调拨预报单更新，code：{}",allocateApplyOrderUpdateDTO.getCode());
//                return Result.fail("OTS-03-001-00-15-052", "调拨预报单正在更新，请稍后在试!");
//            }
        if (Objects.isNull(allocateApplyOrderUpdateDTO.getSourceType())) {
            //判断状态是否可以修改，草稿状态和待推送状态才可以修改
            //待回复状态不能提交
            if (!AllocateApplyOrderStatusEnum.DRAFT.getCode().equals(allocateApplyOrderDetailDTOOld.getResult().getStatus()) || AllocateApplyOrderStatusEnum.TO_BE_SUBMITTED.getCode().equals(allocateApplyOrderDetailDTOOld.getResult().getStatus())) {
                throw new FacadeException("OTS-03-001-00-15-037");
            }
            log.info("AllocateApplyOrderWriteServiceImpl.updateAllocateApplyOrder.update,code:{},data:{}", allocateApplyOrderUpdateDTO.getCode(), JSON.toJSONString(allocateApplyOrderUpdateDTO));
            allocateApplyOrderEntity = AllocateApplyOrderFactory.update(allocateApplyOrderUpdateDTO);
            allocateApplyOrderEntity.update();
        } else {
            log.info("AllocateApplyOrderWriteServiceImpl.updateAllocateApplyOrder.nykUpdate,code:{},data:{}", allocateApplyOrderUpdateDTO.getCode(), JSON.toJSONString(allocateApplyOrderUpdateDTO));
            allocateApplyOrderEntity = AllocateApplyOrderFactory.nykUpdate(allocateApplyOrderUpdateDTO);
            allocateApplyOrderEntity.nykUpdate();
        }
//        } catch (Exception e) {
//            log.error("AllocateApplyOrderWriteServiceImpl.updateAllocateApplyOrder.Exception:", e);
//            return Result.fail(CommonErrorCode.SYSTEM_ERROR, "系统开小差了");
//        }
        log.info("AllocateApplyOrderWriteServiceImpl.updateAllocateApplyOrder.queryAllocateApplyOrderByCode,code:{},data:{}", queryAllocateApplyOrderRequest.getCode(), JSON.toJSONString(queryAllocateApplyOrderRequest));
        Result<AllocateApplyOrderDetailDTO> allocateApplyOrderDetailDTONew = allocateApplyOrderReadService.queryAllocateApplyOrderByCode(queryAllocateApplyOrderRequest);
        log.info("AllocateApplyOrderWriteServiceImpl.updateAllocateApplyOrder.queryAllocateApplyOrderByCode,code:{},resultData:{}", queryAllocateApplyOrderRequest.getCode(), JSON.toJSONString(allocateApplyOrderDetailDTONew));

        //添加单据日志
        Map<String, String> features = new HashMap<>();
        features.put(CODE, queryAllocateApplyOrderRequest.getCode());
        features.put(STATUS, allocateApplyOrderDetailDTONew.getResult().getStatus().toString());
        AllocateApplyOrderDetailDTO allocateApplyOrderDetailOld = allocateApplyOrderDetailDTOOld.getResult();
        AllocateApplyOrderDetailDTO allocateApplyOrderDetailNew = allocateApplyOrderDetailDTONew.getResult();
//        String contrastDetailValue = contrastDetail(allocateApplyOrderDetailOld.getList(), allocateApplyOrderDetailNew.getList());
//        features.put(ALLOCATE_APPLY_ORDER_DETAIL, contrastDetailValue);
        saveDocumentLog(allocateApplyOrderDetailOld, allocateApplyOrderDetailNew, Integer.valueOf(AllocateApplyOrderOperationTypeEnum.UPDATE.getValue()), features);
        log.info("AllocateApplyOrderWriteServiceImpl.updateAllocateApplyOrder,result:{}", JSON.toJSONString(Result.success(true)));
        return Result.success(true);
    }


    private String contrastDetail(List<AllocateApplyOrderGoodsDetailDTO> olds, List<AllocateApplyOrderGoodsDetailDTO> news) {
        //将转换的对象封装成map
        Map<String, List<AllocateApplyOrderGoodsDetailDTO>> contrastDetailResult = new HashMap<>();
        if (CollectionUtils.isNotEmpty(olds) && CollectionUtils.isNotEmpty(news)) {
            //提取新老对象物料编码用于比较
            List<String> oldList = new ArrayList<>();
            List<String> newList = new ArrayList<>();
            //新老关闭的值
            List<String> oldClosedList = new ArrayList<>();
            List<String> newClosedList = new ArrayList<>();

            //新老值转map
            Map<String, AllocateApplyOrderGoodsDetailDTO> oldMap = new HashMap<>();
            Map<String, AllocateApplyOrderGoodsDetailDTO> newMap = new HashMap<>();

            //老值循环
            for (AllocateApplyOrderGoodsDetailDTO allocateApplyOrderGoodsDetailDTO : olds) {
                oldList.add(allocateApplyOrderGoodsDetailDTO.getScItemId());
                oldMap.put(allocateApplyOrderGoodsDetailDTO.getScItemId(), allocateApplyOrderGoodsDetailDTO);
                if (Objects.nonNull(allocateApplyOrderGoodsDetailDTO.getIsClosed()) && 1 == allocateApplyOrderGoodsDetailDTO.getIsClosed()) {
                    oldClosedList.add(allocateApplyOrderGoodsDetailDTO.getScItemId());
                }
            }
            //新值循环
            for (AllocateApplyOrderGoodsDetailDTO allocateApplyOrderGoodsDetailDTO : news) {
                newList.add(allocateApplyOrderGoodsDetailDTO.getScItemId());
                newMap.put(allocateApplyOrderGoodsDetailDTO.getScItemId(), allocateApplyOrderGoodsDetailDTO);
                if (Objects.nonNull(allocateApplyOrderGoodsDetailDTO.getIsClosed()) && 1 == allocateApplyOrderGoodsDetailDTO.getIsClosed()) {
                    newClosedList.add(allocateApplyOrderGoodsDetailDTO.getScItemId());
                }
            }
            //新增的值
            List<String> addScItemIds = new ArrayList<>(newList);
            addScItemIds.removeAll(oldList);
            //删除的值
            List<String> deleteScItemIds = new ArrayList<>(oldList);
            deleteScItemIds.removeAll(newList);
            //关闭的值
            List<String> closeScItemIds = new ArrayList<>(newClosedList);
            closeScItemIds.removeAll(oldClosedList);

            //创建3个对象分别获取区分开的对象
            List<AllocateApplyOrderGoodsDetailDTO> addDetails = new ArrayList<>();
            List<AllocateApplyOrderGoodsDetailDTO> deleteDetails = new ArrayList<>();
            List<AllocateApplyOrderGoodsDetailDTO> closeDetails = new ArrayList<>();
            for (String scItemId : addScItemIds) {
                AllocateApplyOrderGoodsDetailDTO allocateApplyOrderGoodsDetailDTO = newMap.get(scItemId);
                if (Objects.nonNull(allocateApplyOrderGoodsDetailDTO)) {
                    addDetails.add(allocateApplyOrderGoodsDetailDTO);
                }
            }
            for (String scItemId : deleteScItemIds) {
                AllocateApplyOrderGoodsDetailDTO allocateApplyOrderGoodsDetailDTO = oldMap.get(scItemId);
                if (Objects.nonNull(allocateApplyOrderGoodsDetailDTO)) {
                    deleteDetails.add(allocateApplyOrderGoodsDetailDTO);
                }
            }
            for (String scItemId : closeScItemIds) {
                AllocateApplyOrderGoodsDetailDTO allocateApplyOrderGoodsDetailDTO = newMap.get(scItemId);
                if (Objects.nonNull(allocateApplyOrderGoodsDetailDTO)) {
                    closeDetails.add(allocateApplyOrderGoodsDetailDTO);
                }
            }
            if (CollectionUtils.isNotEmpty(deleteDetails)) {
                contrastDetailResult.put("deleteDetails", deleteDetails);
            }
            if (CollectionUtils.isNotEmpty(closeDetails)) {
                contrastDetailResult.put("closeDetails", closeDetails);
            }
            if (CollectionUtils.isNotEmpty(addDetails)) {
                contrastDetailResult.put("addDetails", addDetails);
            }
            return JSON.toJSONString(contrastDetailResult);
        }

        if (CollectionUtils.isNotEmpty(news)) {
            contrastDetailResult.put("addDetails", news);
            return JSON.toJSONString(contrastDetailResult);
        }
        if (CollectionUtils.isNotEmpty(olds)) {
            contrastDetailResult.put("deleteDetails", olds);
            return JSON.toJSONString(contrastDetailResult);
        }
        return "";
    }

    @Override
    @FacadeInvoker(value = "SAP更新预报单", errorCode = "OTS-03-001-00-15-030")
    public Result<Boolean> sapUpdateAllocateApplyOrder(AllocateApplyOrderUpdateDTO allocateApplyOrderUpdateDTO) {
        QueryAllocateApplyOrderRequest queryAllocateApplyOrderRequest = new QueryAllocateApplyOrderRequest();
        queryAllocateApplyOrderRequest.setCode(allocateApplyOrderUpdateDTO.getCode());
        log.info("AllocateApplyOrderWriteServiceImpl.sapUpdateAllocateApplyOrder.queryAllocateApplyOrderByCode,code:{},data:{}", queryAllocateApplyOrderRequest.getCode(), JSON.toJSONString(queryAllocateApplyOrderRequest));
        Result<AllocateApplyOrderDetailDTO> allocateApplyOrderDetailDTOOld = allocateApplyOrderReadService.queryAllocateApplyOrderByCode(queryAllocateApplyOrderRequest);
        log.info("AllocateApplyOrderWriteServiceImpl.updateAllocateApplyOrder.queryAllocateApplyOrderByCode,code:{},allocateApplyOrderDetailDTOOldResultData:{}", queryAllocateApplyOrderRequest.getCode(), JSON.toJSONString(allocateApplyOrderDetailDTOOld));

        //查找货品信息
        Set<String> codes = allocateApplyOrderUpdateDTO.getList().stream().map(AllocateApplyOrderDetailCreateDTO::getScItemId).collect(Collectors.toSet());
//        QueryGoodsListUnifiedInventoryRequest allocateApplyOrderQueryGoodsListRequest = new QueryGoodsListUnifiedInventoryRequest();
//        allocateApplyOrderQueryGoodsListRequest.setGoodsCodes(new ArrayList(codes));
//        log.info("AllocateApplyOrderWriteServiceImpl.sapUpdateAllocateApplyOrder.queryGoodsListUnifiedInventory,code:{},data:{}", queryAllocateApplyOrderRequest.getCode(), allocateApplyOrderQueryGoodsListRequest);
//        QueryGoodsListUnifiedInventoryResponse queryGoodsListResponse = platformEnhanceService.queryGoodsListUnifiedInventory(allocateApplyOrderQueryGoodsListRequest);
//        log.info("AllocateApplyOrderWriteServiceImpl.updateAllocateApplyOrder.queryGoodsListUnifiedInventory,code:{},queryGoodsListUnifiedInventoryResultData:{}", queryAllocateApplyOrderRequest.getCode(), queryGoodsListResponse);
//        List<AllocateApplyOrderQueryGoodsListResponse> scItemGoodsList = new ArrayList<>();
//        if (Objects.nonNull(queryGoodsListResponse)) {
//            List result = queryGoodsListResponse.getResult();
//            if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(result)) {
//                scItemGoodsList = JSONObject.parseArray(JSONObject.toJSONString(result), AllocateApplyOrderQueryGoodsListResponse.class);
//            }
//        }


        Map<String, AllocateOrderDetailBatchGetScItemResponse> scItemMapByOutCodes = InfoUtil.getScItemMapByOutCodes
                (CollectionUtils.isNotEmpty(codes) ? new ArrayList<>(codes) : null);
        if (scItemMapByOutCodes != null) {
            for (AllocateApplyOrderDetailCreateDTO allocateApplyOrderDetailCreateDTO : allocateApplyOrderUpdateDTO.getList()) {
                AllocateOrderDetailBatchGetScItemResponse scItemResponse = scItemMapByOutCodes.get(allocateApplyOrderDetailCreateDTO.getScItemId());
                if (scItemResponse != null) {
                    allocateApplyOrderDetailCreateDTO.setScItemId(scItemResponse.getScItemCode());
                    allocateApplyOrderDetailCreateDTO.setTitle(scItemResponse.getTitle());
                }
            }
        }
        //将货品信息转换成map  -- 因为scItemGoodsList 获取的数据不全 所以改用上面的方法获取货品
//        if (CollectionUtils.isNotEmpty(scItemGoodsList)) {
//            Map<String, AllocateApplyOrderQueryGoodsListDateilResponse> map = new HashMap<>();
//            for (AllocateApplyOrderQueryGoodsListResponse allocateApplyOrderQueryGoodsListResponse : scItemGoodsList) {
//                for (AllocateApplyOrderQueryGoodsListDateilResponse allocateApplyOrderQueryGoodsListDateilResponse : allocateApplyOrderQueryGoodsListResponse.getGoodsList()) {
//                    map.put(allocateApplyOrderQueryGoodsListDateilResponse.getGoodsCode(), allocateApplyOrderQueryGoodsListDateilResponse);
//                }
//            }
//            for (AllocateApplyOrderDetailCreateDTO allocateApplyOrderDetailCreateDTO : allocateApplyOrderUpdateDTO.getList()) {
//                AllocateApplyOrderQueryGoodsListDateilResponse allocateApplyOrderQueryGoodsListDateilResponse = map.get(allocateApplyOrderDetailCreateDTO.getScItemId());
//                if (Objects.nonNull(allocateApplyOrderQueryGoodsListDateilResponse)) {
//                    allocateApplyOrderDetailCreateDTO.setScItemId(allocateApplyOrderQueryGoodsListDateilResponse.getGoodsCode());
//                    allocateApplyOrderDetailCreateDTO.setTitle(allocateApplyOrderQueryGoodsListDateilResponse.getGoodsName());
//                }
//            }
//        }
        //获取收货仓档案信息
        if (Objects.nonNull(allocateApplyOrderUpdateDTO.getShipWarehouseId())) {
            WmsSDO shipWmsSDO = InfoUtil.getWmsSDO(allocateApplyOrderUpdateDTO.getShipWarehouseId());
            if (Objects.nonNull(shipWmsSDO) && Objects.nonNull(shipWmsSDO.getWarehouseId())) {
                allocateApplyOrderUpdateDTO.setShipCargoZoneId(shipWmsSDO.getWarehouseId());
            }
        }
        log.info("AllocateApplyOrderWriteServiceImpl.sapUpdateAllocateApplyOrder.sapUpdate,code:{},data:{}", allocateApplyOrderUpdateDTO.getCode(), JSON.toJSONString(allocateApplyOrderUpdateDTO));
        AllocateApplyOrderEntity allocateApplyOrderEntity = AllocateApplyOrderFactory.sapUpdate(allocateApplyOrderUpdateDTO);
        allocateApplyOrderEntity.sapUpdate();
        log.info("AllocateApplyOrderWriteServiceImpl.sapUpdateAllocateApplyOrder.queryAllocateApplyOrderByCode,code:{},data:{}", queryAllocateApplyOrderRequest.getCode(), JSON.toJSONString(queryAllocateApplyOrderRequest));
        Result<AllocateApplyOrderDetailDTO> allocateApplyOrderDetailDTONew = allocateApplyOrderReadService.queryAllocateApplyOrderByCode(queryAllocateApplyOrderRequest);
        log.info("AllocateApplyOrderWriteServiceImpl.sapUpdateAllocateApplyOrder.queryAllocateApplyOrderByCode,code:{},allocateApplyOrderDetailDTONewResultData:{}", queryAllocateApplyOrderRequest.getCode(), JSON.toJSONString(allocateApplyOrderDetailDTONew));
        //添加单据日志
        Map<String, String> features = new HashMap<>();
        features.put(CODE, queryAllocateApplyOrderRequest.getCode());
        features.put(STATUS, allocateApplyOrderDetailDTONew.getResult().getStatus().toString());
        AllocateApplyOrderDetailDTO allocateApplyOrderDetailOld = allocateApplyOrderDetailDTOOld.getResult();
        AllocateApplyOrderDetailDTO allocateApplyOrderDetailNew = allocateApplyOrderDetailDTONew.getResult();
//        String contrastDetailValue = contrastDetail(allocateApplyOrderDetailOld.getList(), allocateApplyOrderDetailNew.getList());
//        features.put(ALLOCATE_APPLY_ORDER_DETAIL, contrastDetailValue);
        saveDocumentLog(allocateApplyOrderDetailOld, allocateApplyOrderDetailNew, Integer.valueOf(AllocateApplyOrderOperationTypeEnum.UPDATE.getValue()), features);
        return Result.success(true);
    }

    @Override
    @FacadeInvoker(value = "提交预调拨单", errorCode = "OTS-03-001-00-15-035")
    public Result<Boolean> submitAllocateApplyOrder(AllocateApplyOrderUpdateDTO allocateApplyOrderUpdateDTO) {

        //查询调拨预报单
        QueryAllocateApplyOrderRequest queryAllocateApplyOrderRequest = new QueryAllocateApplyOrderRequest();
        queryAllocateApplyOrderRequest.setCode(allocateApplyOrderUpdateDTO.getCode());
        log.info("AllocateApplyOrderWriteServiceImpl.submitAllocateApplyOrder.queryAllocateApplyOrderByCode,code:{},data:{}", queryAllocateApplyOrderRequest.getCode(), JSON.toJSONString(queryAllocateApplyOrderRequest));
        Result<AllocateApplyOrderDetailDTO> allocateApplyOrderDetailDTOOld = allocateApplyOrderReadService.queryAllocateApplyOrderByCode(queryAllocateApplyOrderRequest);
        log.info("AllocateApplyOrderWriteServiceImpl.submitAllocateApplyOrder.queryAllocateApplyOrderByCode,code:{},allocateApplyOrderDetailDTOOldResultData:{}", queryAllocateApplyOrderRequest.getCode(), JSON.toJSONString(queryAllocateApplyOrderRequest));
        //判断时间是否正确
        //单据日期
        if (Objects.nonNull(allocateApplyOrderUpdateDTO.getOrderTime())){
            if (!isDateError(allocateApplyOrderUpdateDTO.getOrderTime())){
                throw new FacadeException("OTS-03-001-00-15-085");
            }
        }
        //期望交货日期
        if (Objects.nonNull(allocateApplyOrderUpdateDTO.getHopeDeliveryTime())){
            if (!isDateError(allocateApplyOrderUpdateDTO.getHopeDeliveryTime())){
                throw new FacadeException("OTS-03-001-00-15-086");
            }
        }

        //获取预报单类型
        if (Objects.nonNull(allocateApplyOrderDetailDTOOld) && Objects.nonNull(allocateApplyOrderDetailDTOOld.getResult())) {
            allocateApplyOrderUpdateDTO.setType(allocateApplyOrderDetailDTOOld.getResult().getType());
        }

        //草稿和待推送状态下才可以提交
        //2022.07.05 调拨预报单订单共享平台回复时, 可以回复
        if (!AllocateApplyOrderStatusEnum.DRAFT.getCode().equals(allocateApplyOrderDetailDTOOld.getResult().getStatus())
                && !AllocateApplyOrderStatusEnum.TO_BE_SUBMITTED.getCode().equals(allocateApplyOrderDetailDTOOld.getResult().getStatus())
            && !Objects.equals(allocateApplyOrderDetailDTOOld.getResult().getType(),AllocateOrderTypeEnum.CROSS_COMPANY.getType().toString())) {
            throw new FacadeException("OTS-03-001-00-15-013");
        }
        //查询货品单位
        List<AllocateApplyOrderDetailCreateDTO> allocateApplyOrderDetailCreateS = allocateApplyOrderUpdateDTO.getList();
        if (CollectionUtils.isEmpty(allocateApplyOrderDetailCreateS)) {
            throw new FacadeException("OTS-03-001-00-15-006");
        }
        getUom(allocateApplyOrderDetailCreateS);
        /**
         * 判断是否走sap
         * 1.计划调拨
         * 推sap，
         * 2、总部销售调拨
         * 工厂直发客户 isDTC	是	推sap
         * 否情况 再看发货仓 shipWarehouseType	是工厂还是共享仓 是工厂推sap 工厂编码是：5
         * 不是（是共享仓）	走平台
         */
        Boolean isSAP = false;
        if (DocumentTypeEnum.PLANNED_ALLOCATION.getCode().equals(allocateApplyOrderUpdateDTO.getType())) {
            isSAP = true;
        } else {
            if (DocumentTypeEnum.HEADQUARTERS_SALES_ALLOCATION.getCode().equals(allocateApplyOrderUpdateDTO.getType())) {
                if (allocateApplyOrderUpdateDTO.getIsDTC()) {
                    isSAP = true;
                } else {
                    //查找库存信息
                    QueryCargoZoneByIdRequest queryCargoZoneByIdRequest = new QueryCargoZoneByIdRequest();
                    queryCargoZoneByIdRequest.setCargoZoneIdList(Lists.newArrayList(allocateApplyOrderUpdateDTO.getShipWarehouseId()));
                    log.info("AllocateApplyOrderWriteServiceImpl.submitAllocateApplyOrder.queryCargoZoneById,code:{},data:{}", queryAllocateApplyOrderRequest.getCode(), JSON.toJSONString(queryCargoZoneByIdRequest));
                    QueryCargoZoneByIdResponse queryCargoZoneByIdResponse = unifiedInventoryService.queryCargoZoneById(queryCargoZoneByIdRequest);
                    log.info("AllocateApplyOrderWriteServiceImpl.submitAllocateApplyOrder.queryCargoZoneById,code:{},queryCargoZoneByIdResponseResultData:{}", queryAllocateApplyOrderRequest.getCode(), JSON.toJSONString(queryCargoZoneByIdResponse));
                    if (Objects.nonNull(queryCargoZoneByIdResponse) && CollectionUtils.isNotEmpty(queryCargoZoneByIdResponse.getResult())) {
                        Map<String, String> result = (Map<String, String>) queryCargoZoneByIdResponse.getResult().get(0);
                        Object resultType = result.get(TYPE_STRING);
                        String type = NULL_STRING;
                        if (Objects.nonNull(resultType)) {
                            type = resultType.toString();
                            type = type.substring(0, type.indexOf("."));
                        }
                        //解决共享仓没有推sap问题
                        if ("5".equals(type)||"2".equals(type)) {
                            isSAP = true;
                        }
                    }
                }
            }
        }

        AllocateApplyOrderEntity allocateApplyOrderEntity;
        //借货调拨进入别的状态
        if (DocumentTypeEnum.CROSS_COMPANY_BORROW_GOODS_ALLOCATION.getCode().equals(allocateApplyOrderUpdateDTO.getType())) {
            //状态是总部回复，就修改为客户回复状态，否则修改总部回复状态
            if (AllocateStatusEnum.HEADQUARTERS_REPLY.getCode().equals(allocateApplyOrderDetailDTOOld.getResult().getStatus())) {
                log.info("AllocateApplyOrderWriteServiceImpl.submitAllocateApplyOrder.shipperSubmit,code:{},data:{}", allocateApplyOrderUpdateDTO.getCode(), JSON.toJSONString(allocateApplyOrderUpdateDTO));
                allocateApplyOrderEntity = AllocateApplyOrderFactory.shipperSubmit(allocateApplyOrderUpdateDTO);
                log.info("AllocateApplyOrderWriteServiceImpl.submitAllocateApplyOrder.shipperSubmit,code:{},allocateApplyOrderEntityResultData:{}", allocateApplyOrderUpdateDTO.getCode(), JSON.toJSONString(allocateApplyOrderUpdateDTO));
            } else {
                log.info("AllocateApplyOrderWriteServiceImpl.submitAllocateApplyOrder.headquartersSubmit,code:{},data:{}", allocateApplyOrderUpdateDTO.getCode(), JSON.toJSONString(allocateApplyOrderUpdateDTO));
                allocateApplyOrderEntity = AllocateApplyOrderFactory.headquartersSubmit(allocateApplyOrderUpdateDTO);
                log.info("AllocateApplyOrderWriteServiceImpl.submitAllocateApplyOrder.headquartersSubmit,code:{},allocateApplyOrderEntityResultData:{}", allocateApplyOrderUpdateDTO.getCode(), JSON.toJSONString(allocateApplyOrderUpdateDTO));
            }
        } else {
            //判断是否推sap，推SAP状态改为待提交状态，不推sap状态改为待回复状态
            if (isSAP) {
                log.info("AllocateApplyOrderWriteServiceImpl.submitAllocateApplyOrder.toBeSubmitted,code:{},data:{}", allocateApplyOrderUpdateDTO.getCode(), JSON.toJSONString(allocateApplyOrderUpdateDTO));
                allocateApplyOrderUpdateDTO.setSapEndProcessing(1);
                allocateApplyOrderEntity = AllocateApplyOrderFactory.toBeSubmitted(allocateApplyOrderUpdateDTO);
                log.info("AllocateApplyOrderWriteServiceImpl.submitAllocateApplyOrder.toBeSubmitted,code:{},allocateApplyOrderEntityResultData:{}", allocateApplyOrderUpdateDTO.getCode(), JSON.toJSONString(allocateApplyOrderUpdateDTO));
            } else {
                log.info("AllocateApplyOrderWriteServiceImpl.submitAllocateApplyOrder.submit,code:{},data:{}", allocateApplyOrderUpdateDTO.getCode(), JSON.toJSONString(allocateApplyOrderUpdateDTO));
                allocateApplyOrderUpdateDTO.setSapEndProcessing(0);
                allocateApplyOrderEntity = AllocateApplyOrderFactory.submit(allocateApplyOrderUpdateDTO);
                log.info("AllocateApplyOrderWriteServiceImpl.submitAllocateApplyOrder.submit,code:{},allocateApplyOrderEntityResultData:{}", allocateApplyOrderUpdateDTO.getCode(), JSON.toJSONString(allocateApplyOrderUpdateDTO));
            }
        }
//        try (RedisLock lock = new RedisLock(BcOtsConstants.REDIS_CACHE_CODE(), allocateApplyOrderUpdateDTO.getCode())) {
//            boolean locked = lock.lock();
//            if (!locked) {
//                log.error("调拨预报单更新，code：{}",allocateApplyOrderUpdateDTO.getCode());
//                return Result.fail("OTS-03-001-00-15-052", "调拨预报单正在更新，请稍后在试!");
//            }
        allocateApplyOrderEntity.update();
//        } catch (Exception e) {
//            log.error("AllocateApplyOrderWriteServiceImpl.updateAllocateApplyOrder.Exception:", e);
//            return Result.fail(CommonErrorCode.SYSTEM_ERROR, "系统开小差了");
//        }
        log.info("AllocateApplyOrderWriteServiceImpl.submitAllocateApplyOrder.queryAllocateApplyOrderByCode,queryAllocateApplyOrderByCode:{},data:{}", allocateApplyOrderUpdateDTO.getCode(), JSON.toJSONString(allocateApplyOrderUpdateDTO));
        Result<AllocateApplyOrderDetailDTO> allocateApplyOrderDetailDTONew = allocateApplyOrderReadService.queryAllocateApplyOrderByCode(queryAllocateApplyOrderRequest);
        log.info("AllocateApplyOrderWriteServiceImpl.submitAllocateApplyOrder.queryAllocateApplyOrderByCode,code:{},allocateApplyOrderDetailDTONewResultData:{}", allocateApplyOrderUpdateDTO.getCode(), JSON.toJSONString(allocateApplyOrderUpdateDTO));
        //添加单据日志
        Map<String, String> features = new HashMap<>();
        features.put(CODE, queryAllocateApplyOrderRequest.getCode());
        features.put(STATUS, allocateApplyOrderDetailDTONew.getResult().getStatus().toString());
        saveDocumentLog(allocateApplyOrderDetailDTOOld.getResult(), allocateApplyOrderDetailDTONew.getResult(), Integer.valueOf(AllocateApplyOrderOperationTypeEnum.SUBMIT.getValue()), features);
        //区分预报单类型，传sap
        if (isSAP) {
            allocateApplyOrderPushToSAP(allocateApplyOrderUpdateDTO.getCode());
        }
        return Result.success(true);
    }

    private void allocateApplyOrderPushToSAP(String code) {
        AllocateApplyOrderUpdateDTO allocateApplyOrderUpdateDTO = new AllocateApplyOrderUpdateDTO();
        QueryAllocateApplyOrderRequest queryAllocateApplyOrderRequest = new QueryAllocateApplyOrderRequest();
        queryAllocateApplyOrderRequest.setCode(code);
        log.info("AllocateApplyOrderWriteServiceImpl.allocateApplyOrderPushToSAP.queryAllocateApplyOrderByCode,code:{}", queryAllocateApplyOrderRequest.getCode());
        Result<AllocateApplyOrderDetailDTO> allocateApplyOrderDetailDTOResult = allocateApplyOrderReadService.queryAllocateApplyOrderByCode(queryAllocateApplyOrderRequest);
        log.info("AllocateApplyOrderWriteServiceImpl.allocateApplyOrderPushToSAP.queryAllocateApplyOrderByCode,code:{},allocateApplyOrderDetailDTOResultResultData:{}", code, JSON.toJSONString(allocateApplyOrderDetailDTOResult));
        AllocateApplyOrderDetailDTO allocateApplyOrderDetailDTO = allocateApplyOrderDetailDTOResult.getResult();
        BeanUtils.copyProperties(allocateApplyOrderDetailDTO, allocateApplyOrderUpdateDTO);
        //复制主数据前将前端传来的明细拿出来
        List<AllocateApplyOrderGoodsDetailDTO> allocateApplyOrderGoodsDetailDTOS = allocateApplyOrderDetailDTO.getList();
        List<AllocateApplyOrderDetailCreateDTO> allocateApplyOrderDetailCreateDTOS = new ArrayList<>();
        //获取单位
        for (AllocateApplyOrderGoodsDetailDTO allocateApplyOrderGoodsDetailDTO : allocateApplyOrderGoodsDetailDTOS) {
            AllocateApplyOrderDetailCreateDTO allocateApplyOrderDetailCreateDTO = new AllocateApplyOrderDetailCreateDTO();
            BeanUtils.copyProperties(allocateApplyOrderGoodsDetailDTO, allocateApplyOrderDetailCreateDTO);

            allocateApplyOrderDetailCreateDTOS.add(allocateApplyOrderDetailCreateDTO);
        }
        allocateApplyOrderUpdateDTO.setList(allocateApplyOrderDetailCreateDTOS);
        //sap需要的数据
        //发货工厂code
        allocateApplyOrderUpdateDTO.setDeliveryFactoryCode(allocateApplyOrderDetailDTO.getFactoryCode());
        //库存code
        if (StringUtils.isNotEmpty(allocateApplyOrderDetailDTO.getStockCode()) && OtsUnifiedInventoryConstants.DEFAULT().equals(allocateApplyOrderDetailDTO.getStockCode())) {
            allocateApplyOrderUpdateDTO.setDeliveryInventoryCode(null);
        } else {
            allocateApplyOrderUpdateDTO.setDeliveryInventoryCode(allocateApplyOrderDetailDTO.getStockCode());
        }
        allocateApplyOrderUpdateDTO.setCustomerAddress(allocateApplyOrderDetailDTO.getAddresscode());
        allocateApplyOrderUpdateDTO.setCustomer(allocateApplyOrderDetailDTO.getCustomerCode());
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DATE_FORMAT);//注意月份是MM
        try {
            allocateApplyOrderUpdateDTO.setTakeEffectTime(simpleDateFormat.parse(allocateApplyOrderDetailDTO.getTakeEffectTime()));
            allocateApplyOrderUpdateDTO.setHopeDeliveryTime(simpleDateFormat.parse(allocateApplyOrderDetailDTO.getHopeDeliveryTime()));
            allocateApplyOrderUpdateDTO.setInvalidDate(simpleDateFormat.parse(allocateApplyOrderDetailDTO.getInvalidDate()));
        } catch (ParseException e) {
            log.error("allocateApplyOrderPushToSAP date transformation", e);
        }
        if (Objects.nonNull(allocateApplyOrderDetailDTO.getGoodsGroup())) {
            allocateApplyOrderUpdateDTO.setGoodsGroup(allocateApplyOrderDetailDTO.getGoodsGroup().toString());
        }
        //单位
        List<String> scItemIds = allocateApplyOrderDetailDTO.getList().stream().map(AllocateApplyOrderGoodsDetailDTO::getScItemId).collect(Collectors.toList());

        QueryGoodsListUnifiedInventoryRequest queryGoodsListUnifiedInventoryRequest = new QueryGoodsListUnifiedInventoryRequest();
        queryGoodsListUnifiedInventoryRequest.setGoodsCodes(scItemIds);
        // TODO: 2021/12/2 万文洋 日志打印把关键信息记录下来，如id，code等
        log.info("AllocateApplyOrderWriteServiceImpl.allocateApplyOrderPushToSAP.queryGoodsListUnifiedInventory,code:{},data:{}", allocateApplyOrderDetailDTO.getCode(), JSON.toJSONString(queryGoodsListUnifiedInventoryRequest));
        QueryGoodsListUnifiedInventoryResponse queryGoodsListUnifiedInventoryResponse = platformEnhanceService.queryGoodsListUnifiedInventory(queryGoodsListUnifiedInventoryRequest);
        log.info("AllocateApplyOrderWriteServiceImpl.allocateApplyOrderPushToSAP.queryGoodsListUnifiedInventory,code:{},queryGoodsListUnifiedInventoryResponseResltData:{}", allocateApplyOrderDetailDTO.getCode(), JSON.toJSONString(queryGoodsListUnifiedInventoryResponse));
        List<AllocateApplyOrderQueryGoodsListResponse> scItemGoodsList = null;
        if (null != queryGoodsListUnifiedInventoryResponse) {
            List result = queryGoodsListUnifiedInventoryResponse.getResult();
            if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(result)) {
                scItemGoodsList = com.alibaba.fastjson.JSONObject.parseArray(JSONObject.toJSONString(result), AllocateApplyOrderQueryGoodsListResponse.class);
            }
            List<AllocateApplyOrderQueryGoodsListDateilResponse> goodsList = scItemGoodsList.get(0).getGoodsList();
            Map<String, String> queryGoodsListDateilMap = new HashMap<>();
            for (AllocateApplyOrderQueryGoodsListDateilResponse queryGoodsListDateilResponse : goodsList) {
                queryGoodsListDateilMap.put(queryGoodsListDateilResponse.getGoodsCode(), queryGoodsListDateilResponse.getBaseUnitCode());
            }
            List<AllocateApplyOrderDetailCreateDTO> allocateApplyOrderDetailCreates = allocateApplyOrderUpdateDTO.getList();
            for (AllocateApplyOrderDetailCreateDTO allocateApplyOrderDetailCreateDTO : allocateApplyOrderDetailCreates) {
                allocateApplyOrderDetailCreateDTO.setUom(queryGoodsListDateilMap.get(allocateApplyOrderDetailCreateDTO.getScItemId()));
            }
            //总部内部售达方编号
            allocateApplyOrderUpdateDTO.setSapInternalSalesBPCode(allocateApplyOrderDetailDTO.getSapInternalSalesBPCode());
            //总部内部送达方编号
            allocateApplyOrderUpdateDTO.setSapInternalDeliveryBPCode(allocateApplyOrderDetailDTO.getSapInternalDeliveryBPCode());
            //总部售达方编号
            allocateApplyOrderUpdateDTO.setSapSalesBPCode(allocateApplyOrderDetailDTO.getSapSalesBPCode());
            //总部送达方编号
            allocateApplyOrderUpdateDTO.setSapDeliveryBPCode(allocateApplyOrderDetailDTO.getSapDeliveryBPCode());
            allocateApplyOrderUpdateDTO.setList(allocateApplyOrderDetailCreates);
        }
        //@todo wwy 集成测试暂时处理
        allocateApplyOrderUpdateDTO.setGmtCreate(new Date());
        //发送mq消息
        String message = JSON.toJSONString(allocateApplyOrderUpdateDTO);
        log.info("AllocateApplyOrderWriteServiceImpl.allocateApplyOrderPushToSAP.sendMessage,code:{},data:{}", allocateApplyOrderDetailDTO.getCode(), JSON.toJSONString(message));
        Boolean aBoolean = messageService.sendMessage(OtsUnifiedInventoryConstants.ALLOCATE_APPLY_ORDER_MQ_CODE(), OtsUnifiedInventoryConstants.ALLOCATE_APPLY_ORDER_TOPIC(), OtsUnifiedInventoryConstants.ALLOCATE_APPLY_ORDER_TAG(), allocateApplyOrderDetailDTO.getCode(), message);

    }

    private void getUom(List<AllocateApplyOrderDetailCreateDTO> allocateApplyOrderDetailCreateDTOS) {

        List<String> ids = allocateApplyOrderDetailCreateDTOS.stream().map(AllocateApplyOrderDetailCreateDTO::getScItemId).collect(Collectors.toList());
        QueryGoodsListUnifiedInventoryRequest allocateApplyOrderQueryGoodsListRequest = new QueryGoodsListUnifiedInventoryRequest();
        allocateApplyOrderQueryGoodsListRequest.setGoodsCodes(ids);
        //查询货品
        log.info("AllocateApplyOrderWriteServiceImpl.getUom.queryGoodsListUnifiedInventory,goodsCode:{},data:{}", allocateApplyOrderQueryGoodsListRequest.getGoodsCodes(), JSON.toJSONString(allocateApplyOrderQueryGoodsListRequest));
        QueryGoodsListUnifiedInventoryResponse queryGoodsListResponse = platformEnhanceService.queryGoodsListUnifiedInventory(allocateApplyOrderQueryGoodsListRequest);
        log.info("AllocateApplyOrderWriteServiceImpl.getUom.queryGoodsListUnifiedInventory,goodsCode:{},data:{}", allocateApplyOrderQueryGoodsListRequest.getGoodsCodes(), JSON.toJSONString(queryGoodsListResponse));
        List<AllocateApplyOrderQueryGoodsListResponse> scItemGoodsList = null;
        if (Objects.nonNull(queryGoodsListResponse)) {
            List result = queryGoodsListResponse.getResult();
            if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(result)) {
                scItemGoodsList = JSONObject.parseArray(JSONObject.toJSONString(result), AllocateApplyOrderQueryGoodsListResponse.class);
            }
        }
        //获取货品单位
        if (CollectionUtils.isNotEmpty(scItemGoodsList)) {
            Map<String, AllocateApplyOrderQueryGoodsListDateilResponse> map = new HashMap<>();
            for (AllocateApplyOrderQueryGoodsListResponse allocateApplyOrderQueryGoodsListResponse : scItemGoodsList) {
                for (AllocateApplyOrderQueryGoodsListDateilResponse allocateApplyOrderQueryGoodsListDateilResponse : allocateApplyOrderQueryGoodsListResponse.getGoodsList()) {
                    map.put(allocateApplyOrderQueryGoodsListDateilResponse.getGoodsCode(), allocateApplyOrderQueryGoodsListDateilResponse);
                }
            }
            for (AllocateApplyOrderDetailCreateDTO allocateApplyOrderDetailCreateDTO : allocateApplyOrderDetailCreateDTOS) {
                AllocateApplyOrderQueryGoodsListDateilResponse allocateApplyOrderQueryGoodsListDateilResponse = map.get(allocateApplyOrderDetailCreateDTO.getScItemId());
                if (Objects.nonNull(allocateApplyOrderQueryGoodsListDateilResponse)) {
                    allocateApplyOrderDetailCreateDTO.setUom(allocateApplyOrderQueryGoodsListDateilResponse.getBaseUnitCode());
                    allocateApplyOrderDetailCreateDTO.setUomName(allocateApplyOrderQueryGoodsListDateilResponse.getBaseUnitName());
                }
            }
        }
    }

    /**
     * service层不应该加事务，后面要改造，调整到资源层
     */
    @Override
    @FacadeInvoker(value = "回复预调拨单", errorCode = "OTS-03-001-00-15-034")
    @EpochTransactional(appCode = "bc_ots", dataSourceCode = "cr_ots", dataSourceType = "app")
    public Result<Object> replyAllocateApplyOrder(AllocateApplyOrderReplyDTO allocateApplyOrderReplyDTO) {
        //查询预报单数据用于验证
        QueryAllocateApplyOrderRequest queryAllocateApplyOrderRequest = new QueryAllocateApplyOrderRequest();
        queryAllocateApplyOrderRequest.setCode(allocateApplyOrderReplyDTO.getCode());
        log.info("AllocateApplyOrderWriteServiceImpl.replyAllocateApplyOrder.queryAllocateApplyOrderByCode,code:{},data:{}", queryAllocateApplyOrderRequest.getCode(), JSON.toJSONString(queryAllocateApplyOrderRequest));
        Result<AllocateApplyOrderDetailDTO> result = allocateApplyOrderReadService.queryAllocateApplyOrderByCode(queryAllocateApplyOrderRequest);
        log.info("AllocateApplyOrderWriteServiceImpl.replyAllocateApplyOrder.queryAllocateApplyOrderByCode,code:{},queryAllocateApplyOrderByCodeResultData:{}", queryAllocateApplyOrderRequest.getCode(), JSON.toJSONString(result));
        Result<Object> replyAllocateApplyOrderResult = new Result<>();
        if (Objects.isNull(result.getResult())) {
            replyAllocateApplyOrderResult.setMessage("没找到对应预报单");
            replyAllocateApplyOrderResult.success(false);
            return replyAllocateApplyOrderResult;
        }
        AllocateApplyOrderDetailDTO allocateApplyOrderDetailDTO = result.getResult();
        //判断状态能否回复
        if (AllocateStatusEnum.DRAFT.getCode() == allocateApplyOrderDetailDTO.getStatus()
                || AllocateStatusEnum.COMPLETED.getCode() == allocateApplyOrderDetailDTO.getStatus()
                || AllocateStatusEnum.CLOSED.getCode() == allocateApplyOrderDetailDTO.getStatus()
                || AllocateStatusEnum.CANCELLED.getCode() == allocateApplyOrderDetailDTO.getStatus()) {
            replyAllocateApplyOrderResult.setMessage("回复状态才可以回复！");
            replyAllocateApplyOrderResult.success(false);
            return replyAllocateApplyOrderResult;
        }
        //考虑双回复场景，双回复提交需要库中的数据进行校验
        if (DocumentTypeEnum.CROSS_COMPANY_BORROW_GOODS_ALLOCATION.getCode().equals(allocateApplyOrderDetailDTO.getType())) {
            //判断回复数量，如果不是关闭的 回复为0 就报错，没有明细也报错
            if (Objects.nonNull(allocateApplyOrderReplyDTO.getList())) {
                for (AllocateApplyOrderGoodsDetailDTO allocateApplyOrderGoodsDetailDTO : allocateApplyOrderDetailDTO.getList()) {
                    if ((Objects.isNull(allocateApplyOrderGoodsDetailDTO.getIsClosed()) ||
                            0 == allocateApplyOrderGoodsDetailDTO.getIsClosed()) &&
                            0 == allocateApplyOrderGoodsDetailDTO.getDeliverQuantity()
                            && !Objects.equals(allocateApplyOrderGoodsDetailDTO.getStatus(), 5)) {

                        replyAllocateApplyOrderResult.setMessage("发货数量不能为空");
                        replyAllocateApplyOrderResult.success(false);
                        return replyAllocateApplyOrderResult;
                    }
                }
            } else {
                replyAllocateApplyOrderResult.setMessage("明细不能为空");
                replyAllocateApplyOrderResult.success(false);
                return replyAllocateApplyOrderResult;
            }
        } else {
            //判断回复数量，如果不是关闭的 回复为0 就报错，没有明细也报错
            if (Objects.nonNull(allocateApplyOrderReplyDTO.getList())) {
                for (AllocateApplyOrderDetailCreateDTO allocateApplyOrderDetailCreateDTO : allocateApplyOrderReplyDTO.getList()) {
                    if ((Objects.isNull(allocateApplyOrderDetailCreateDTO.getIsClosed()) || 0 == allocateApplyOrderDetailCreateDTO.getIsClosed())
                            && 0 == allocateApplyOrderDetailCreateDTO.getDeliverQuantity()
                            && !Objects.equals(allocateApplyOrderDetailCreateDTO.getStatus(), 5)) {
                        replyAllocateApplyOrderResult.setMessage("发货数量不能为空");
                        replyAllocateApplyOrderResult.success(false);
                        return replyAllocateApplyOrderResult;
                    }
                }
            } else {
                replyAllocateApplyOrderResult.setMessage("明细不能为空");
                replyAllocateApplyOrderResult.success(false);
                return replyAllocateApplyOrderResult;
            }
        }
        allocateApplyOrderReplyDTO.setType(result.getResult().getType());
        log.info("AllocateApplyOrderWriteServiceImpl.replyAllocateApplyOrder.reply,code:{},data:{}", allocateApplyOrderReplyDTO.getCode(), JSON.toJSONString(allocateApplyOrderReplyDTO));
        AllocateApplyOrderEntity allocateApplyOrderEntity = AllocateApplyOrderFactory.reply(allocateApplyOrderReplyDTO);
        allocateApplyOrderEntity.update();
        //总部回复不进创建调拨单和还货单逻辑
        if (!AllocateApplyOrderStatusEnum.HEADQUARTERS_REPLY.getCode().equals(allocateApplyOrderDetailDTO.getStatus())) {

            //判断是否创建调拨单
            List<AllocateApplyOrderDetailCreateDTO> allocateApplyOrderDetailCreateDTOS = new ArrayList<>();
            for (AllocateApplyOrderDetailCreateDTO allocateApplyOrderDetailCreateDTO : allocateApplyOrderReplyDTO.getList()) {
                //判断回复0、状态完成、关闭的 不创建
                if (Objects.nonNull(allocateApplyOrderDetailCreateDTO.getDeliverQuantity()) && allocateApplyOrderDetailCreateDTO.getDeliverQuantity() != 0
                        && !(AllocateApplyOrderStatusEnum.CLOSED.getCode().equals(allocateApplyOrderDetailCreateDTO.getStatus())
                        || AllocateApplyOrderStatusEnum.COMPLETED.getCode().equals(allocateApplyOrderDetailCreateDTO.getStatus()))) {
                    if (Objects.isNull(allocateApplyOrderDetailCreateDTO.getIsClosed()) || 1 != allocateApplyOrderDetailCreateDTO.getIsClosed()) {
                        allocateApplyOrderDetailCreateDTOS.add(allocateApplyOrderDetailCreateDTO);
                    }
                }
            }
            Result<AllocateOrderCreateResponse> allocateOrderCreateRequest = null;
            if (CollectionUtils.isNotEmpty(allocateApplyOrderDetailCreateDTOS)) {
                allocateOrderCreateRequest = createAllocateOrder(allocateApplyOrderReplyDTO.getCode(), allocateApplyOrderDetailCreateDTOS);
                //判断调拨单是否创建成功
                if (Objects.isNull(allocateOrderCreateRequest) || Objects.isNull(allocateOrderCreateRequest.getResult())) {
                    replyAllocateApplyOrderResult.setMessage("调拨单创建失败");
                    replyAllocateApplyOrderResult.success(false);
                    return replyAllocateApplyOrderResult;
                }
            }
            //如果类型是借货类型且需要还货创建还货预报单
            if (Objects.nonNull(allocateApplyOrderReplyDTO.getType()) && FOUR_STRING.equals(allocateApplyOrderReplyDTO.getType())) {
                //判断明细中是否有需要还货的货品
                Boolean isReturnGoods = false;
                for (AllocateApplyOrderDetailCreateDTO allocateApplyOrderDetailCreateDTO : allocateApplyOrderReplyDTO.getList()) {
                    if (YES.equals(allocateApplyOrderDetailCreateDTO.getReturnGood()) && !(AllocateApplyOrderStatusEnum.CLOSED.getCode().equals(allocateApplyOrderDetailCreateDTO.getStatus())
                            || AllocateApplyOrderStatusEnum.COMPLETED.getCode().equals(allocateApplyOrderDetailCreateDTO.getStatus()))) {
                        if (Objects.isNull(allocateApplyOrderDetailCreateDTO.getIsClosed()) || 1 != allocateApplyOrderDetailCreateDTO.getIsClosed()) {
                            isReturnGoods = true;
                        }
                    }
                }
                //判断明细中是否有需要还货的货品，没有就不创建
                if (isReturnGoods && Objects.nonNull(allocateOrderCreateRequest)) {
                    log.info("AllocateApplyOrderWriteServiceImpl.replyAllocateApplyOrder.createReturnGoods,code:{},allocateOrderId:{},allocateApplyOrderReplyDTO:{},allocateApplyOrderDetailDTO:{}",
                            queryAllocateApplyOrderRequest.getCode(), allocateOrderCreateRequest.getResult().getId(), JSON.toJSONString(allocateApplyOrderReplyDTO), JSON.toJSONString(allocateApplyOrderDetailDTO));
                    createReturnGoods(allocateOrderCreateRequest.getResult().getId(), allocateApplyOrderReplyDTO, allocateApplyOrderDetailDTO);
                }
            }
        }
        log.info("AllocateApplyOrderWriteServiceImpl.replyAllocateApplyOrder.queryAllocateApplyOrderByCode,code:{},data:{}", queryAllocateApplyOrderRequest.getCode(), JSON.toJSONString(queryAllocateApplyOrderRequest));
        Result<AllocateApplyOrderDetailDTO> resultNew = allocateApplyOrderReadService.queryAllocateApplyOrderByCode(queryAllocateApplyOrderRequest);
        log.info("AllocateApplyOrderWriteServiceImpl.replyAllocateApplyOrder.queryAllocateApplyOrderByCode,code:{},queryAllocateApplyOrderByCodeNewResultData:{}", queryAllocateApplyOrderRequest.getCode(), JSON.toJSONString(resultNew));
        //添加单据日志
        Map<String, String> features = new HashMap<>();
        features.put(CODE, queryAllocateApplyOrderRequest.getCode());
        features.put(STATUS, resultNew.getResult().getStatus().toString());
        saveDocumentLog(result.getResult(), resultNew.getResult(), Integer.valueOf(AllocateApplyOrderOperationTypeEnum.REPLY.getValue()), features);
        return Result.success(true);
    }

    private void createReturnGoods(String allocateOrderId, AllocateApplyOrderReplyDTO allocateApplyOrderReplyDTO, AllocateApplyOrderDetailDTO allocateApplyOrderDetailDTO) {
        AllocateApplyOrderCreateDTO allocateApplyOrderCreateDTO = new AllocateApplyOrderCreateDTO();
        allocateApplyOrderCreateDTO.setType(PLAN_TYPE);
        allocateApplyOrderCreateDTO.setApplyOrgId(allocateApplyOrderDetailDTO.getApplyOrg());
        allocateApplyOrderCreateDTO.setGoodsGroup(allocateApplyOrderDetailDTO.getGoodsGroup());
        //收货仓改成发货仓
        if (Objects.nonNull(allocateApplyOrderDetailDTO.getShipWarehouseId())) {
            allocateApplyOrderCreateDTO.setReceiveWarehouseId(Integer.valueOf(allocateApplyOrderDetailDTO.getShipWarehouseId()));
//            allocateApplyOrderCreateDTO.setReceiveCargoZoneId(Integer.valueOf(allocateApplyOrderDetailDTO.getre));
        }
        //获取收货仓档案信息
        if (Objects.nonNull(allocateApplyOrderCreateDTO.getReceiveWarehouseId())) {
            WmsSDO shipWmsSDO = InfoUtil.getWmsSDO(allocateApplyOrderCreateDTO.getReceiveWarehouseId().toString());
            if (Objects.nonNull(shipWmsSDO) && Objects.nonNull(shipWmsSDO.getWarehouseId())) {
                allocateApplyOrderCreateDTO.setReceiveCargoZoneId(Integer.valueOf(shipWmsSDO.getWarehouseId()));
            }
        }
        //发货工厂 取默认第一个工厂类型仓库
        WmsQueryWarehouseZoneListRequest wmsQueryWarehouseZoneListRequest = new WmsQueryWarehouseZoneListRequest();
        wmsQueryWarehouseZoneListRequest.setType(5);
        wmsQueryWarehouseZoneListRequest.setStatus(1);
        WmsQueryWarehouseZoneListResponse wmsQueryWarehouseZoneListResponse = unifiedInventoryService.wmsQueryWarehouseZoneList(wmsQueryWarehouseZoneListRequest);
        log.info("AllocateApplyOrderWriteServiceImpl.createReturnGoods.queryAllocateApplyOrderByCode,wmsQueryWarehouseZoneListResponseData:{}", JSON.toJSONString(wmsQueryWarehouseZoneListResponse));
        if (Objects.nonNull(wmsQueryWarehouseZoneListResponse) && Objects.nonNull(wmsQueryWarehouseZoneListResponse.getResult())) {
            allocateApplyOrderCreateDTO.setShipWarehouseId(wmsQueryWarehouseZoneListResponse.getResult().get(0).getId());
            allocateApplyOrderCreateDTO.setShipCargoZoneId(wmsQueryWarehouseZoneListResponse.getResult().get(0).getWarehouseId());
        }
        Date date = new Date();
        allocateApplyOrderCreateDTO.setOrderTime(date);
        allocateApplyOrderCreateDTO.setTakeEffectTime(date);
        allocateApplyOrderCreateDTO.setInvalidDate(date);
        allocateApplyOrderCreateDTO.setShipMethod(allocateApplyOrderDetailDTO.getShipMethod());
        allocateApplyOrderCreateDTO.setSapRefPoNo(allocateApplyOrderDetailDTO.getSapRefPoNo());
        allocateApplyOrderCreateDTO.setSapCostCenter(allocateApplyOrderDetailDTO.getSapCostCenter());
        //通过发货工厂id查找逻辑仓库中所需要的数据
        if (Objects.nonNull(allocateApplyOrderDetailDTO.getShipWarehouseId())) {
            QueryCargoZoneByIdRequest queryCargoZoneByIdRequest = new QueryCargoZoneByIdRequest();
            queryCargoZoneByIdRequest.setCargoZoneIdList(Lists.newArrayList(allocateApplyOrderDetailDTO.getShipWarehouseId()));
            log.info("AllocateApplyOrderWriteServiceImpl.createReturnGoods.queryCargoZoneById,cargoZoneIdList:{}", JSONObject.toJSONString(queryCargoZoneByIdRequest.getCargoZoneIdList()));
            QueryCargoZoneByIdResponse queryCargoZoneByIdResponse = unifiedInventoryService.queryCargoZoneById(queryCargoZoneByIdRequest);
            log.info("AllocateApplyOrderWriteServiceImpl.createReturnGoods.queryCargoZoneById,cargoZoneIdList:{},queryCargoZoneByIdResponseData", JSONObject.toJSONString(queryCargoZoneByIdRequest.getCargoZoneIdList()), queryCargoZoneByIdResponse);
            if (Objects.nonNull(queryCargoZoneByIdResponse) && CollectionUtils.isNotEmpty(queryCargoZoneByIdResponse.getResult())) {
                Map<String, String> resultShipWarehouse = (Map<String, String>) queryCargoZoneByIdResponse.getResult().get(0);
                //总部内部售达方编号
                allocateApplyOrderCreateDTO.setSapInternalSalesBPCode(resultShipWarehouse.get(SAP_INTERNAL_SALES_BP_CODE));
                //总部内部送达方编号
                allocateApplyOrderCreateDTO.setSapInternalDeliveryBPCode(resultShipWarehouse.get(SAP_INTERNAL_DELIVERY_BP_CODE));
                //总部售达方编号
                allocateApplyOrderCreateDTO.setSapSalesBPCode(resultShipWarehouse.get(SAP_SALE_BP_CODE));
                //总部送达方编号
                allocateApplyOrderCreateDTO.setSapDeliveryBPCode(resultShipWarehouse.get(SAP_DELIVERY_BP_CODE));
            }
        }
        allocateApplyOrderCreateDTO.setIsDTC(false);
        allocateApplyOrderCreateDTO.setHeadquartersChannelCode(allocateApplyOrderDetailDTO.getHeadquartersChannelCode());
        allocateApplyOrderCreateDTO.setHeadquartersOrganizationCode(allocateApplyOrderDetailDTO.getHeadquartersOrganizationCode());
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.add(Calendar.DAY_OF_MONTH, 1);
        allocateApplyOrderCreateDTO.setHopeDeliveryTime(c.getTime());
        allocateApplyOrderCreateDTO.setDocumentReason(allocateApplyOrderDetailDTO.getDocumentReason());
        //操作人
        allocateApplyOrderCreateDTO.setOperator(allocateApplyOrderDetailDTO.getCreatorId());
        //插入调拨预报单
        log.info("AllocateApplyOrderWriteServiceImpl.createReturnGoods.create,data:{}", JSONObject.toJSONString(allocateApplyOrderCreateDTO));
        AllocateApplyOrderEntity allocateApplyOrderCreateEntity = AllocateApplyOrderFactory.create(allocateApplyOrderCreateDTO);
        String code = allocateApplyOrderCreateEntity.create();
        AllocateApplyOrderUpdateDTO allocateApplyOrderUpdateDTO = new AllocateApplyOrderUpdateDTO();
        BeanUtils.copyProperties(allocateApplyOrderCreateDTO, allocateApplyOrderUpdateDTO);
        List<AllocateApplyOrderDetailCreateDTO> allocateApplyOrderDetailCreateDTOS = new ArrayList<>();
        Integer num = 1;
        for (AllocateApplyOrderDetailCreateDTO allocateApplyOrderDetailCreateDTO : allocateApplyOrderReplyDTO.getList()) {
            if (YES.equals(allocateApplyOrderDetailCreateDTO.getReturnGood()) && !(AllocateApplyOrderStatusEnum.CLOSED.getCode().equals(allocateApplyOrderDetailCreateDTO.getStatus())
                    || AllocateApplyOrderStatusEnum.COMPLETED.getCode().equals(allocateApplyOrderDetailCreateDTO.getStatus()))) {
                if (Objects.isNull(allocateApplyOrderDetailCreateDTO.getIsClosed()) || 1 != allocateApplyOrderDetailCreateDTO.getIsClosed()) {
                    allocateApplyOrderDetailCreateDTO.setApplyQuantity(allocateApplyOrderDetailCreateDTO.getDeliverQuantity());
                    allocateApplyOrderDetailCreateDTO.setReplyQuantity(0);
                    allocateApplyOrderDetailCreateDTO.setDeliverQuantity(0);
                    allocateApplyOrderDetailCreateDTO.setLineNo(num);
                    allocateApplyOrderDetailCreateDTO.setExchangeAmt(null);
                    allocateApplyOrderDetailCreateDTOS.add(allocateApplyOrderDetailCreateDTO);
                    num = num + 1;
                }
            }
        }
        QueryAllocateApplyOrderRequest queryAllocateApplyOrderRequest = new QueryAllocateApplyOrderRequest();
        queryAllocateApplyOrderRequest.setCode(code);
        log.info("AllocateApplyOrderWriteServiceImpl.createReturnGoods.create,code:{},data:{}", queryAllocateApplyOrderRequest.getCode(), JSONObject.toJSONString(queryAllocateApplyOrderRequest));
        Result<AllocateApplyOrderDetailDTO> allocateApplyOrderDetailDTOResult = allocateApplyOrderReadService.queryAllocateApplyOrderByCode(queryAllocateApplyOrderRequest);
        log.info("AllocateApplyOrderWriteServiceImpl.createReturnGoods.create,code:{},allocateApplyOrderDetailDTOResultData:{}", queryAllocateApplyOrderRequest.getCode(), JSONObject.toJSONString(allocateApplyOrderDetailDTOResult));
        //获取预报单类型
        if (Objects.nonNull(allocateApplyOrderDetailDTOResult) && Objects.nonNull(allocateApplyOrderDetailDTOResult.getResult())) {
            allocateApplyOrderUpdateDTO.setId(allocateApplyOrderDetailDTOResult.getResult().getId());
        }
        LoadAllocateOrderRequest loadAllocateOrderRequest = new LoadAllocateOrderRequest();
        loadAllocateOrderRequest.setId(allocateOrderId);
        log.info("AllocateApplyOrderWriteServiceImpl.createReturnGoods.create,code:{},data:{}", queryAllocateApplyOrderRequest.getCode(), JSONObject.toJSONString(queryAllocateApplyOrderRequest));
        AllocateOrder allocateOrder = allocateOrderService.loadAllocateOrder(loadAllocateOrderRequest);
        log.info("AllocateApplyOrderWriteServiceImpl.createReturnGoods.create,code:{},allocateOrderData:{}", queryAllocateApplyOrderRequest.getCode(), JSONObject.toJSONString(allocateOrder));
        //获取调拨
        if (Objects.nonNull(allocateApplyOrderDetailDTOResult) && Objects.nonNull(allocateApplyOrderDetailDTOResult.getResult())) {
            allocateApplyOrderUpdateDTO.setBorrowGoodsTransfer0rderCode(allocateOrder.getCode());
        }
        allocateApplyOrderUpdateDTO.setList(allocateApplyOrderDetailCreateDTOS);
        allocateApplyOrderUpdateDTO.setCode(code);
        allocateApplyOrderUpdateDTO.setGmtCreate(new Date());
        //@Todo wwy 还货时暂时没有默认账号，有了在加
        allocateApplyOrderUpdateDTO.setCreator("平台默认管理员");
        //修改状态且推sap
        submitAllocateApplyOrder(allocateApplyOrderUpdateDTO);
    }

    //创建调拨单
    private Result<AllocateOrderCreateResponse> createAllocateOrder(String code, List<AllocateApplyOrderDetailCreateDTO> allocateApplyOrderDetailCreateDTOS) {
        QueryAllocateApplyOrderRequest queryAllocateApplyOrderRequest = new QueryAllocateApplyOrderRequest();
        queryAllocateApplyOrderRequest.setCode(code);
        Result<AllocateApplyOrderDetailDTO> result = allocateApplyOrderReadService.queryAllocateApplyOrderByCode(queryAllocateApplyOrderRequest);
        AllocateApplyOrderDetailDTO allocateApplyOrderDetailDTO = result.getResult();
        AllocateOrderCreateRequest allocateOrderCreateRequest = new AllocateOrderCreateRequest();
        allocateOrderCreateRequest.setAllocateApplyOrderId(allocateApplyOrderDetailDTO.getId() + NULL_STRING);
        allocateOrderCreateRequest.setAllocateApplyOrderCode(allocateApplyOrderDetailDTO.getCode());
        allocateOrderCreateRequest.setApplyOrgId(allocateApplyOrderDetailDTO.getApplyOrg() == null ? NULL_STRING : allocateApplyOrderDetailDTO.getApplyOrg().toString());
        //收货工厂  收货工厂取发货工厂的
        allocateOrderCreateRequest.setReceiveWareHouseId(allocateApplyOrderDetailDTO.getShipWarehouseId() == null ? NULL_STRING : allocateApplyOrderDetailDTO.getShipWarehouseId());
        //发货工厂 取默认第一个工厂的
        allocateOrderCreateRequest.setShipWareHouseId(allocateApplyOrderDetailDTO.getReceiveWarehouseId() == null ? NULL_STRING : allocateApplyOrderDetailDTO.getReceiveWarehouseId());
        allocateOrderCreateRequest.setSapRefPoNo(allocateApplyOrderDetailDTO.getSapRefPoNo());
        allocateOrderCreateRequest.setType(Integer.valueOf(allocateApplyOrderDetailDTO.getType()));
        allocateOrderCreateRequest.setCreateTime(allocateApplyOrderDetailDTO.getGmtCreate());
//        allocateOrderCreateRequest.setConfirmTime(allocateApplyOrderDetailDTO.getCommitTime());
        allocateOrderCreateRequest.setShipMethod(Integer.valueOf(allocateApplyOrderDetailDTO.getShipMethod()));
//        allocateOrderCreateRequest.setSendBackRequired(allocateApplyOrderDetailDTO.getReturnGood()==null?false:allocateApplyOrderDetailDTO.getReturnGood()==1?true:false);
//        allocateOrderCreateRequest.setStatus(allocateApplyOrderDetailDTO.getStatus().toString());
        allocateOrderCreateRequest.setFounder(allocateApplyOrderDetailDTO.getCreator());
        allocateOrderCreateRequest.setCreator(allocateApplyOrderDetailDTO.getCreator());
        allocateOrderCreateRequest.setCustomer(allocateApplyOrderDetailDTO.getCustomerCode());
        allocateOrderCreateRequest.setBranchCustomersCode(allocateApplyOrderDetailDTO.getBranchCustomersCode());
        List<AllocateOrderScItemDetailDTO> allocateOrderScItemDetailDTOS = new ArrayList<>();
        Map<String, AllocateApplyOrderGoodsDetailDTO> map = new HashMap<>();
        for (AllocateApplyOrderGoodsDetailDTO allocateApplyOrderGoodsDetailDTO : allocateApplyOrderDetailDTO.getList()) {
            map.put(allocateApplyOrderGoodsDetailDTO.getScItemId(), allocateApplyOrderGoodsDetailDTO);
        }
        for (AllocateApplyOrderDetailCreateDTO allocateApplyOrderDetailCreateDTO : allocateApplyOrderDetailCreateDTOS) {
            AllocateApplyOrderGoodsDetailDTO allocateApplyOrderGoodsDetailDTO = map.get(allocateApplyOrderDetailCreateDTO.getScItemId());
            AllocateOrderScItemDetailDTO allocateOrderScItemDetailDTO = new AllocateOrderScItemDetailDTO();
            allocateOrderScItemDetailDTO.setOutAllocateOrderLineId(null == allocateApplyOrderGoodsDetailDTO.getOutLineNo() ? NULL_STRING : allocateApplyOrderGoodsDetailDTO.getOutLineNo().toString());
            allocateOrderScItemDetailDTO.setAllocateApplyOrderLineNo(null == allocateApplyOrderGoodsDetailDTO.getLineNo() ? NULL_STRING : allocateApplyOrderGoodsDetailDTO.getLineNo().toString());
            allocateOrderScItemDetailDTO.setScItemCode(allocateApplyOrderGoodsDetailDTO.getScItemId());
            allocateOrderScItemDetailDTO.setScItemName(allocateApplyOrderGoodsDetailDTO.getTitle());
            allocateOrderScItemDetailDTO.setApplyQuantity(null == allocateApplyOrderGoodsDetailDTO.getApplyQuantity() ? NULL_STRING : allocateApplyOrderGoodsDetailDTO.getApplyQuantity().toString());
            allocateOrderScItemDetailDTO.setQuantity(null == allocateApplyOrderDetailCreateDTO.getDeliverQuantity() ? NULL_STRING : allocateApplyOrderDetailCreateDTO.getDeliverQuantity().toString());
            allocateOrderScItemDetailDTO.setConfirmQuantity(null == allocateApplyOrderDetailCreateDTO.getDeliverQuantity() ? NULL_STRING : allocateApplyOrderDetailCreateDTO.getDeliverQuantity().toString());
            allocateOrderScItemDetailDTO.setUnitPrice(null == allocateApplyOrderGoodsDetailDTO.getUnitPrice() ? NULL_STRING : allocateApplyOrderGoodsDetailDTO.getUnitPrice().toString());
            allocateOrderScItemDetailDTO.setDiscount(null == allocateApplyOrderGoodsDetailDTO.getDiscount() ? NULL_STRING : allocateApplyOrderGoodsDetailDTO.getDiscount().toString());
            allocateOrderScItemDetailDTO.setSubTotalAmount(null == allocateApplyOrderGoodsDetailDTO.getSubtotalMoney() ? NULL_STRING : allocateApplyOrderGoodsDetailDTO.getSubtotalMoney().toString());
            allocateOrderScItemDetailDTO.setReplyQuantity(null == allocateApplyOrderGoodsDetailDTO.getDeliverQuantity() ? NULL_STRING : allocateApplyOrderGoodsDetailDTO.getDeliverQuantity().toString());
            allocateOrderScItemDetailDTO.setScItemId(allocateApplyOrderGoodsDetailDTO.getGoodsId());
            allocateOrderScItemDetailDTO.setExpectedProduceDate(getDate(allocateApplyOrderGoodsDetailDTO.getProductionTime()));
            if (allocateApplyOrderGoodsDetailDTO.getExchangeAmt() != null) {
                allocateOrderScItemDetailDTO.setExchangeAmt(allocateApplyOrderGoodsDetailDTO.getExchangeAmt().toString());
            }
            //加下备注
            allocateOrderScItemDetailDTO.setRemarks(allocateApplyOrderGoodsDetailDTO.getRemark());

            allocateOrderScItemDetailDTOS.add(allocateOrderScItemDetailDTO);
        }
        allocateOrderCreateRequest.setAllocateOrderScItemDetails(allocateOrderScItemDetailDTOS);
        //调拨单保存 没有明细不创建调拨单
        if (CollectionUtils.isNotEmpty(allocateOrderScItemDetailDTOS)) {
            return allocateOrderWriteService.create(allocateOrderCreateRequest);
        } else {
            AllocateOrderCreateResponse allocateOrderCreateResponse = new AllocateOrderCreateResponse();
            return Result.success(allocateOrderCreateResponse);
        }
    }

    @Override
    @FacadeInvoker(value = "取消调拨预报单", errorCode = "OTS-03-001-00-15-033")
    public Result<Boolean> cancelAllocateApplyOrder(CancelAllocateApplyOrderRequest request) {

        log.info("AllocateApplyOrderWriteServiceImpl.cancelAllocateApplyOrder,request:{}", JSON.toJSONString(request));
        //1.查询预报单
        QueryAllocateApplyOrderRequest queryAllocateApplyOrderRequest = new QueryAllocateApplyOrderRequest();
        queryAllocateApplyOrderRequest.setCode(request.getCode());
        //查询预调拨单
        log.info("AllocateApplyOrderWriteServiceImpl.cancelAllocateApplyOrder.queryAllocateApplyOrderByCode,allocateApplyOrderResponseCode:{},data:{}", queryAllocateApplyOrderRequest.getCode(), JSON.toJSONString(queryAllocateApplyOrderRequest));
        AllocateApplyOrderResponse allocateApplyOrderResponse = allocateApplyOrderReadRepository.queryAllocateApplyOrderByCode(queryAllocateApplyOrderRequest.getCode());
        log.info("AllocateApplyOrderWriteServiceImpl.cancelAllocateApplyOrder.queryAllocateApplyOrderByCode,result:{}", JSON.toJSONString(allocateApplyOrderResponse));
        if (null == allocateApplyOrderResponse.getAllocateApplyOrderDetailDTO() ||
                null == allocateApplyOrderResponse.getAllocateApplyOrderDetailDTO().getId()) {
            throw new FacadeException("OTS-03-001-00-15-003");
        }
        AllocateApplyOrderDetailDTO allocateApplyOrderDetailDTO = allocateApplyOrderResponse.getAllocateApplyOrderDetailDTO();

        if (!AllocateApplyOrderStatusEnum.DRAFT.getCode().equals(allocateApplyOrderDetailDTO.getStatus())) {
            throw new FacadeException("OTS-03-001-00-15-012");
        }
        //查询预调拨单详情
        List<AllocateApplyOrderGoodsDetailDTO> allocateApplyOrderGoodsDetailDTOs = new ArrayList<>();
        if (Objects.nonNull(allocateApplyOrderDetailDTO.getId())) {
            log.info("AllocateApplyOrderWriteServiceImpl.cancelAllocateApplyOrder.loadDetailByOrderId,request:{}", allocateApplyOrderDetailDTO.getId().toString());
            allocateApplyOrderGoodsDetailDTOs = allocateApplyOrderDetailReadRepository.loadDetailByOrderId(allocateApplyOrderDetailDTO.getId());
            log.info("AllocateApplyOrderWriteServiceImpl.cancelAllocateApplyOrder.loadDetailByOrderId,result:{}", JSON.toJSONString(allocateApplyOrderGoodsDetailDTOs));
        }
        AllocateApplyOrderUpdateDTO allocateApplyOrderUpdateDTO = new AllocateApplyOrderUpdateDTO();
        BeanUtils.copyProperties(allocateApplyOrderDetailDTO, allocateApplyOrderUpdateDTO);
        allocateApplyOrderUpdateDTO.setStatus(AllocateStatusEnum.CANCELLED.getCode());
        List<AllocateApplyOrderDetailCreateDTO> list = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(allocateApplyOrderGoodsDetailDTOs)) {
            for (AllocateApplyOrderGoodsDetailDTO allocateApplyOrderGoodsDetailDTO : allocateApplyOrderGoodsDetailDTOs) {
                AllocateApplyOrderDetailCreateDTO allocateApplyOrderDetailCreateDTO = new AllocateApplyOrderDetailCreateDTO();
                BeanUtils.copyProperties(allocateApplyOrderGoodsDetailDTO, allocateApplyOrderDetailCreateDTO);
                allocateApplyOrderDetailCreateDTO.setStatus(AllocateStatusEnum.CANCELLED.getCode());
                list.add(allocateApplyOrderDetailCreateDTO);
            }
            allocateApplyOrderUpdateDTO.setList(list);
        }
        AllocateApplyOrderEntity allocateApplyOrderEntity = AllocateApplyOrderFactory.cancel(allocateApplyOrderUpdateDTO);
        allocateApplyOrderEntity.cancel();

        log.info("AllocateApplyOrderWriteServiceImpl.cancelAllocateApplyOrder.queryAllocateApplyOrderByCode,allocateApplyOrderResponseOldCode:{},data:{}", queryAllocateApplyOrderRequest.getCode(), JSON.toJSONString(queryAllocateApplyOrderRequest));
        AllocateApplyOrderResponse allocateApplyOrderResponseOld = allocateApplyOrderReadRepository.queryAllocateApplyOrderByCode(queryAllocateApplyOrderRequest.getCode());
        log.info("AllocateApplyOrderWriteServiceImpl.cancelAllocateApplyOrder.queryAllocateApplyOrderByCode,allocateApplyOrderResponseOldResult:{}", JSON.toJSONString(allocateApplyOrderResponseOld));
        //添加单据日志
        Map<String, String> features = new HashMap<>();
        features.put(CODE, queryAllocateApplyOrderRequest.getCode());
        features.put(STATUS, allocateApplyOrderResponseOld.getAllocateApplyOrderDetailDTO().getStatus().toString());
        saveDocumentLog(allocateApplyOrderResponseOld.getAllocateApplyOrderDetailDTO(), allocateApplyOrderResponse.getAllocateApplyOrderDetailDTO(), Integer.valueOf(AllocateApplyOrderOperationTypeEnum.CANCEL.getValue()), features);
        log.info("AllocateApplyOrderWriteServiceImpl.cancelAllocateApplyOrder,result:{}", JSON.toJSONString(Result.success(true)));
        return Result.success(true);
    }

    @Override
    @FacadeInvoker(value = "驳回调拨预报单", errorCode = "OTS-03-001-00-15-032")
    public Result<Boolean> rejectAllocateApplyOrder(RejectAllocateApplyOrderRequest rejectAllocateApplyOrderRequest) {
        log.info("AllocateApplyOrderWriteServiceImpl.rejectAllocateApplyOrder,request:{}", JSON.toJSONString(rejectAllocateApplyOrderRequest));
        //1.查询预报单
        QueryAllocateApplyOrderRequest queryAllocateApplyOrderRequest = new QueryAllocateApplyOrderRequest();
        queryAllocateApplyOrderRequest.setCode(rejectAllocateApplyOrderRequest.getCode());
        log.info("AllocateApplyOrderWriteServiceImpl.rejectAllocateApplyOrder.queryAllocateApplyOrderByCode,oldCode:{},data:{}", queryAllocateApplyOrderRequest.getCode(), JSON.toJSONString(queryAllocateApplyOrderRequest));
        Result<AllocateApplyOrderDetailDTO> result = allocateApplyOrderReadService.queryAllocateApplyOrderByCode(queryAllocateApplyOrderRequest);
        log.info("AllocateApplyOrderWriteServiceImpl.rejectAllocateApplyOrder.queryAllocateApplyOrderByCode,oldData:{}", JSON.toJSONString(result));
        if (!(Objects.isNull(result) || Objects.isNull(result.getResult()))) {
            AllocateApplyOrderDetailDTO allocateApplyOrderDetailDTO = result.getResult();
            //判断状态是不是确认回复状态，是的话进行修改
            if (AllocateStatusEnum.WAIT_ANSWER.getCode() == allocateApplyOrderDetailDTO.getStatus()
                    || AllocateStatusEnum.PART_ANSWER.getCode() == allocateApplyOrderDetailDTO.getStatus()
                    || AllocateStatusEnum.SHIPPER_REPLY.getCode() == allocateApplyOrderDetailDTO.getStatus()
                    || AllocateStatusEnum.HEADQUARTERS_REPLY.getCode() == allocateApplyOrderDetailDTO.getStatus()) {
                AllocateApplyOrderUpdateDTO allocateApplyOrderUpdateDTO = new AllocateApplyOrderUpdateDTO();
                BeanUtils.copyProperties(allocateApplyOrderDetailDTO, allocateApplyOrderUpdateDTO);
                allocateApplyOrderUpdateDTO.setStatus(AllocateStatusEnum.CLOSED.getCode());
                List<AllocateApplyOrderDetailCreateDTO> list = new ArrayList<>();
                for (AllocateApplyOrderGoodsDetailDTO allocateApplyOrderGoodsDetailDTO : allocateApplyOrderDetailDTO.getList()) {
                    AllocateApplyOrderDetailCreateDTO allocateApplyOrderDetailCreateDTO = new AllocateApplyOrderDetailCreateDTO();
                    BeanUtils.copyProperties(allocateApplyOrderGoodsDetailDTO, allocateApplyOrderDetailCreateDTO);
                    allocateApplyOrderDetailCreateDTO.setStatus(AllocateStatusEnum.CLOSED.getCode());
                    list.add(allocateApplyOrderDetailCreateDTO);
                }
                allocateApplyOrderUpdateDTO.setList(list);
                AllocateApplyOrderEntity allocateApplyOrderEntity = AllocateApplyOrderFactory.reject(allocateApplyOrderUpdateDTO);
                allocateApplyOrderEntity.update();
                log.info("AllocateApplyOrderWriteServiceImpl.rejectAllocateApplyOrder.queryAllocateApplyOrderByCode,queryAllocateApplyOrderByCodeRequest:{}", JSON.toJSONString(queryAllocateApplyOrderRequest));
                Result<AllocateApplyOrderDetailDTO> allocateApplyOrderDetailDTOResultNew = allocateApplyOrderReadService.queryAllocateApplyOrderByCode(queryAllocateApplyOrderRequest);
                log.info("AllocateApplyOrderWriteServiceImpl.rejectAllocateApplyOrder.queryAllocateApplyOrderByCode,queryAllocateApplyOrderByCodeResult:{}", JSON.toJSONString(allocateApplyOrderDetailDTOResultNew));
                //添加单据日志
                Map<String, String> features = new HashMap<>();
                features.put(CODE, queryAllocateApplyOrderRequest.getCode());
                features.put(STATUS, allocateApplyOrderDetailDTOResultNew.getResult().getStatus().toString());
                saveDocumentLog(result.getResult(), allocateApplyOrderDetailDTOResultNew.getResult(), Integer.valueOf(AllocateApplyOrderOperationTypeEnum.REJECT.getValue()), features);
                log.info("AllocateApplyOrderWriteServiceImpl.rejectAllocateApplyOrder,result:{}", JSON.toJSONString(Result.success(true)));
                return Result.success(true);
            }
            throw new FacadeException("OTS-03-001-00-15-050");
        }
        throw new FacadeException("OTS-03-001-00-15-068");
    }

    @Override
    @FacadeInvoker(value = "复制预报单", errorCode = "OTS-03-001-00-15-031")
    @EpochTransactional(appCode = "bc_ots", dataSourceCode = "cr_ots", dataSourceType = "app")
    public Result<AllocateApplyOrderDetailDTO> copyAllocateApplyOrder(CopyAllocateApplyOrderRequest request) {
        log.info("AllocateApplyOrderWriteServiceImpl.copyAllocateApplyOrder,request:{}", JSON.toJSONString(request));
        //验证参数是否为空
        if (Objects.isNull(request.getCode())) {
            throw new FacadeException("OTS-03-001-00-15-002");
        }
        //查询预报单数据
        QueryAllocateApplyOrderRequest queryAllocateApplyOrderRequest = new QueryAllocateApplyOrderRequest();
        queryAllocateApplyOrderRequest.setCode(request.getCode());
        log.info("AllocateApplyOrderWriteServiceImpl.copyAllocateApplyOrder.queryAllocateApplyOrderByCode,allocateApplyOrderDetailDTORequest:{}", JSON.toJSONString(queryAllocateApplyOrderRequest));
        Result<AllocateApplyOrderDetailDTO> allocateApplyOrderDetailDTOResult = allocateApplyOrderReadService.queryAllocateApplyOrderByCode(queryAllocateApplyOrderRequest);
        log.info("AllocateApplyOrderWriteServiceImpl.copyAllocateApplyOrder.queryAllocateApplyOrderByCode,allocateApplyOrderDetailDTOResultResult:{}", JSON.toJSONString(allocateApplyOrderDetailDTOResult));
        //判断编码是否查找的有数据
        if (Objects.isNull(allocateApplyOrderDetailDTOResult) || Objects.isNull(allocateApplyOrderDetailDTOResult.getResult())) {
            throw new FacadeException("OTS-03-001-00-15-069");
        }
        AllocateApplyOrderDetailDTO allocateApplyOrderDetailDTO = allocateApplyOrderDetailDTOResult.getResult();
        //创建新的预报单
        AllocateApplyOrderCreateDTO allocateApplyOrderCreateDTO = new AllocateApplyOrderCreateDTO();
        BeanUtils.copyProperties(allocateApplyOrderDetailDTO, allocateApplyOrderCreateDTO);
        allocateApplyOrderCreateDTO.setType(Integer.valueOf(allocateApplyOrderDetailDTO.getType()));
        allocateApplyOrderCreateDTO.setApplyOrgId(allocateApplyOrderDetailDTO.getApplyOrg());
        if (Objects.nonNull(allocateApplyOrderDetailDTO.getReceiveWarehouseId()) && !NULL_STRING.equals(allocateApplyOrderDetailDTO.getReceiveWarehouseId())) {
            allocateApplyOrderCreateDTO.setReceiveWarehouseId(Integer.valueOf(allocateApplyOrderDetailDTO.getReceiveWarehouseId()));
        }
        allocateApplyOrderCreateDTO.setOrderTime(getDate(allocateApplyOrderDetailDTO.getOrderTime()));
        allocateApplyOrderCreateDTO.setTakeEffectTime(getDate(allocateApplyOrderDetailDTO.getTakeEffectTime()));
        allocateApplyOrderCreateDTO.setInvalidDate(getDate(allocateApplyOrderDetailDTO.getInvalidDate()));
        allocateApplyOrderCreateDTO.setHopeDeliveryTime(getDate(allocateApplyOrderDetailDTO.getHopeDeliveryTime()));
        allocateApplyOrderCreateDTO.setHeadquartersChannelCode(allocateApplyOrderDetailDTO.getHeadquartersChannelCode());
        allocateApplyOrderCreateDTO.setHeadquartersOrganizationCode(allocateApplyOrderDetailDTO.getHeadquartersOrganizationCode());
        allocateApplyOrderCreateDTO.setOutAllocateApplyOrderId(null);
        //F-b 客户地址
        if (StringUtils.isNotBlank(request.getCode())){
            AllocateApplyOrderLoadListRequest allocateApplyOrderLoadListRequest = new AllocateApplyOrderLoadListRequest();
            allocateApplyOrderLoadListRequest.setCode(request.getCode());
            Result<List<AllocateApplyOrder>> listResult = allocateApplyOrderService.loadAllocateApplyOrderList(allocateApplyOrderLoadListRequest);
            if (listResult != null && CollectionUtils.isNotEmpty(listResult.getResult())){
                AllocateApplyOrder allocateApplyOrder = listResult.getResult().get(0);
                if (StringUtils.isNotBlank(allocateApplyOrder.getCustomer())){
                    allocateApplyOrderCreateDTO.setCustomer(allocateApplyOrder.getCustomer());
                }
                if (StringUtils.isNotBlank(allocateApplyOrder.getCustomerAddress())){
                    allocateApplyOrderCreateDTO.setCustomerAddress(allocateApplyOrder.getCustomerAddress());
                }
            }

        }

        //获取收货仓档案信息
        WmsSDO receiveWarehouse = InfoUtil.getWmsSDO(allocateApplyOrderDetailDTO.getReceiveWarehouseId());
        if (Objects.nonNull(receiveWarehouse) && Objects.nonNull(receiveWarehouse.getWarehouseId())) {
            allocateApplyOrderCreateDTO.setReceiveCargoZoneId(Integer.valueOf(receiveWarehouse.getWarehouseId()));
        }
        //获取发货仓档案信息
        WmsSDO shipWarehouse = InfoUtil.getWmsSDO(allocateApplyOrderDetailDTO.getShipWarehouseId());
        if (Objects.nonNull(shipWarehouse) && Objects.nonNull(shipWarehouse.getWarehouseId())) {
            allocateApplyOrderCreateDTO.setShipCargoZoneId(shipWarehouse.getWarehouseId());
        }


        //插入调拨预报单
        allocateApplyOrderCreateDTO.setGmtCreate(new Date());
        AllocateApplyOrderEntity allocateApplyOrderCreateEntity = AllocateApplyOrderFactory.create(allocateApplyOrderCreateDTO);
        String code = allocateApplyOrderCreateEntity.create();
        //获取新的预报单数据
        queryAllocateApplyOrderRequest.setCode(code);
        log.info("AllocateApplyOrderWriteServiceImpl.copyAllocateApplyOrder.queryAllocateApplyOrderByCode,allocateApplyOrderDetailResultRequest:{}", JSON.toJSONString(queryAllocateApplyOrderRequest));
        Result<AllocateApplyOrderDetailDTO> allocateApplyOrderDetailResult = allocateApplyOrderReadService.queryAllocateApplyOrderByCode(queryAllocateApplyOrderRequest);
        log.info("AllocateApplyOrderWriteServiceImpl.copyAllocateApplyOrder.queryAllocateApplyOrderByCode,allocateApplyOrderDetailResultResult:{}", JSON.toJSONString(allocateApplyOrderDetailResult));
        if (Objects.isNull(allocateApplyOrderDetailResult) || Objects.isNull(allocateApplyOrderDetailResult.getResult())) {
            throw new FacadeException("OTS-03-001-00-15-004");
        }
        AllocateApplyOrderDetailDTO allocateApplyOrderDetai = allocateApplyOrderDetailResult.getResult();
        //需要复制的预报单明细处理，放新的预报单中
        List<AllocateApplyOrderDetailCreateDTO> list = new ArrayList<>();
        for (AllocateApplyOrderGoodsDetailDTO allocateApplyOrderGoodsDetailDTO : allocateApplyOrderDetailDTO.getList()) {
            AllocateApplyOrderDetailCreateDTO allocateApplyOrderDetailCreateDTO = new AllocateApplyOrderDetailCreateDTO();
            allocateApplyOrderDetailCreateDTO.setLineNo(allocateApplyOrderGoodsDetailDTO.getLineNo());
            allocateApplyOrderDetailCreateDTO.setAllocateApplyOrderId(allocateApplyOrderDetai.getId().intValue());
            allocateApplyOrderDetailCreateDTO.setScItemId(allocateApplyOrderGoodsDetailDTO.getScItemId());
            allocateApplyOrderDetailCreateDTO.setTitle(allocateApplyOrderGoodsDetailDTO.getTitle());
            allocateApplyOrderDetailCreateDTO.setGoodsId(allocateApplyOrderGoodsDetailDTO.getGoodsId());
            allocateApplyOrderDetailCreateDTO.setUnitPrice(allocateApplyOrderGoodsDetailDTO.getUnitPrice());
            allocateApplyOrderDetailCreateDTO.setApplyQuantity(allocateApplyOrderGoodsDetailDTO.getApplyQuantity());
            allocateApplyOrderDetailCreateDTO.setStatus(AllocateApplyOrderStatusEnum.DRAFT.getCode());

            list.add(allocateApplyOrderDetailCreateDTO);
        }
//        allocateApplyOrderDetai.setList(list);
//        //进行保存
//        AllocateApplyOrderUpdateDTO allocateApplyOrderUpdateDTO = new AllocateApplyOrderUpdateDTO();
//        BeanUtils.copyProperties(allocateApplyOrderDetai,allocateApplyOrderUpdateDTO);
//        List<AllocateApplyOrderDetailCreateDTO>allocateApplyOrderDetailCreateDTOS = new ArrayList<>();
//        for (AllocateApplyOrderGoodsDetailDTO allocateApplyOrderGoodsDetailDTO:list){
//            AllocateApplyOrderDetailCreateDTO allocateApplyOrderDetailCreateDTO = new AllocateApplyOrderDetailCreateDTO();
//            BeanUtils.copyProperties(allocateApplyOrderGoodsDetailDTO,allocateApplyOrderDetailCreateDTO);
//            allocateApplyOrderDetailCreateDTOS.add(allocateApplyOrderDetailCreateDTO);
//
//        }
//        allocateApplyOrderUpdateDTO.setList(allocateApplyOrderDetailCreateDTOS);
        //保存
        allocateApplyOrderCreateEntity = AllocateApplyOrderFactory.copyDetail(list);
        if ("takeEffect".equals(BcOtsConstants.transactionTestValue())) {
            throw new RuntimeException("runtime Exception");
        }
        allocateApplyOrderCreateEntity.copyDetail();
        log.info("AllocateApplyOrderWriteServiceImpl.copyAllocateApplyOrder.queryAllocateApplyOrderByCode,allocateApplyOrderDetailDTOResultNewRequest:{}", JSON.toJSONString(queryAllocateApplyOrderRequest));
        Result<AllocateApplyOrderDetailDTO> allocateApplyOrderDetailDTOResultNew = allocateApplyOrderReadService.queryAllocateApplyOrderByCode(queryAllocateApplyOrderRequest);
        log.info("AllocateApplyOrderWriteServiceImpl.copyAllocateApplyOrder.queryAllocateApplyOrderByCode,allocateApplyOrderDetailDTOResultNewResult:{}", JSON.toJSONString(allocateApplyOrderDetailDTOResultNew));
        //添加单据日志
        Map<String, String> features = new HashMap<>();
        features.put(CODE, queryAllocateApplyOrderRequest.getCode());
        features.put(STATUS, allocateApplyOrderDetailDTOResultNew.getResult().getStatus().toString());
        saveDocumentLog(allocateApplyOrderDetailDTOResult.getResult(), allocateApplyOrderDetailDTOResultNew.getResult(), Integer.valueOf(AllocateApplyOrderOperationTypeEnum.COPY.getValue()), features);
        log.info("AllocateApplyOrderWriteServiceImpl.copyAllocateApplyOrder,request:{}", JSON.toJSONString(allocateApplyOrderDetailResult));
        return allocateApplyOrderDetailResult;
    }

    @Override
    @FacadeInvoker(value = "调拨预报单导入", errorCode = "OTS-03-001-00-15-029")
    public Result<AllocateApplyOrderImportListRequest> allocateApplyOrderImport(AllocateApplyOrderImportListRequest request) {
        log.info("AllocateApplyOrderWriteServiceImpl.allocateApplyOrderImport,request:{}", JSON.toJSONString(request));
        List<AllocateApplyOrderImportRequest> list = request.getAllocateApplyOrderImportRequest();
        //获取当前登录人的角色和组织判断查看权限
        GetLoginEmployeeInfoResponse loginEmployeeInfo = baseDataService.getLoginEmployeeInfo();
        //是否业务员
        boolean isSalesMan = false;
        Long organizationSDO = null;
        if (Objects.nonNull(loginEmployeeInfo) && Objects.nonNull(loginEmployeeInfo.getOrganizationSDO()) && StringUtils.isNotEmpty(loginEmployeeInfo.getOrganizationSDO().getId())) {
            organizationSDO = Long.valueOf(loginEmployeeInfo.getOrganizationSDO().getId());
            if (CollectionUtils.isNotEmpty(loginEmployeeInfo.getRoles())){
                for (RoleSDO role : loginEmployeeInfo.getRoles()) {
                    if (SALES_MAN_ROLE_CODE.equals(role.getCode())){
                        isSalesMan = true;
                    }
                }
            }
            if (isSalesMan){
                OrganizationSDO orgSDO = loginEmployeeInfo.getOrganizationSDO();
                while (!Objects.equals(103,orgSDO.getType())){
                    BaselineGetOrganizationById2Request baselineGetOrganizationById2Request = new BaselineGetOrganizationById2Request();
                    if (StringUtils.isBlank(orgSDO.getParentId())){
                        log.info("AllocateApplyOrderWriteServiceImpl.allocateApplyOrderImport.salesMan.org.errResult:{}",JSON.toJSONString(orgSDO));
                        break;
                    }
                    baselineGetOrganizationById2Request.setId(orgSDO.getParentId());
                    Result<OrganizationSDO> organizationSDOResult =
                            baseDataService.baselineGetOrganizationById2(baselineGetOrganizationById2Request);
                    if (organizationSDOResult == null || organizationSDOResult.getResult() == null){
                        log.info("AllocateApplyOrderWriteServiceImpl.allocateApplyOrderImport.salesMan.org.errResult:{}",JSON.toJSONString(organizationSDOResult));
                        break;
                    }
                    orgSDO = organizationSDOResult.getResult();
                    if (orgSDO.getType() != null && orgSDO.getType() < 103){
                        log.info("AllocateApplyOrderWriteServiceImpl.allocateApplyOrderImport.salesMan.org.errResult:{}",JSON.toJSONString(organizationSDOResult));
                        break;
                    }
                }
                //如果是分子公司 就把值给填进去 看该分子公司下的
                if (Objects.equals(103,orgSDO.getType())){
                    organizationSDO = Long.parseLong(orgSDO.getId());
                }
            }

        }
        if (org.apache.commons.collections4.CollectionUtils.isEmpty(list)) {
            return Result.success(request);
        }
        /**
         * 校验字段：
         * 调拨预报单号*
         * "1、必填校验 ok
         * 2、输入字符类型（英文大小写、数字）" ok
         * 调拨类型*
         * "1、范围内值校验 ok
         * 2、必填校验" ok
         *是否直发客户*(1:是 0：否）
         * "1、范围内值校验 ok
         * 2、必填校验 ok
         * 3、根据调拨类型判断" ok
         *货品组编码
         * "1、必填校验 ok
         * 2、范围内值校验" ok
         *收货仓编码*
         * "1、必填校验（如果是工厂直发不必填，如果不是工厂直发需要必填）1
         * 2、范围内值校验 ok
         * 3、根据调拨类型校验 ok
         * 4、根据当前提报组织校验" ok
         *
         *发货仓编码*
         * "1、必填校验 ok
         * 2、范围内值校验 ok
         * 3、根据调拨类型校验 ok
         * 4、根据当前提报组织校验" ok
         *客户送达方ID（直发客户必填）
         * "1、是否必填校验（如果是工厂直发必填，如果不是工厂直发不必填） ok
         * 2、范围内值校验 ok
         * 3、根据当前提报组织校验 ok
         *
         * 分公司客户编码（直发客户必填）
         * "1、是否必填校验（如果是工厂直发必填，如果不是工厂直发不必填） ok
         * 2、范围内值校验 ok
         * 3、根据当前提报组织校验 ok
         * 4、根据所选总部客户地址判断" ok
         * 单据日期
         * "1、是否必填校验
         * 2、未填写时导入后根据调拨单类型和当前时间自动填充" ok
         * 订单备注
         * "1、是否必填校验 ok
         * 2、字符长度限制校验 ok
         * 3、不限制输入字符类型" ok
         * 货品编码*
         * "1、必填校验 ok
         * 2、范围内值校验" ok
         * 提报量*
         * "1、必填校验 ok
         * 2、范围内值校验 ok
         * 3、字符类型和范围限制（大于0，数值）" ok
         * 期望交货日期
         * "1、是否必填校验 ok
         * 2、未填写时导入后根据当前时间自动填充（三天后）" ok
         * 生产日期
         * 1、请PD确认是否需要这个字段
         * 结算金额（借货调拨）
         * "1、是否必填校验
         * 2、根据调拨类型做判断
         * 3、字符类型和范围限制（大于0，数值）" ok
         * 行备注
         * "1、是否必填校验
         * 2、字符长度限制校验
         * 3、不限制输入字符类型"
         * 明细行不能超过100行
         */
        //获取货品组 做校验用
        GetScItemGroupSelectResponse scItemGroupSelect = baseDataService.getScItemGroupSelect();
        log.info("AllocateApplyOrderWriteServiceImpl.allocateApplyOrderImport.getScItemGroupSelect,result:{}", JSON.toJSONString(scItemGroupSelect));
        List scItemGroups = scItemGroupSelect.getResult();
        Map<String, String> scItemGroupMap = new HashMap<>();
        for (Object scItemGroup : scItemGroups) {
            JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(scItemGroup));
            scItemGroupMap.put(jsonObject.getString(CODE), jsonObject.getString(CODE));
        }
        log.info("goodFilters pre {}", JSONObject.toJSONString(request));
        List<AllocateApplyOrderImportRequest> goodFilters = list.stream().collect(Collectors.collectingAndThen(
                Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(
                        AllocateApplyOrderImportRequest::getScItemId))), ArrayList::new));
        List<String> goods = goodFilters.stream().map(AllocateApplyOrderImportRequest::getScItemId).collect(Collectors.toList());
        log.info("goodFilters middle {}", JSONObject.toJSONString(goods));
        List<AllocateApplyOrderQueryGoodsListDateilResponse> goodsListDateilResponse = this.checkGoodsCode(goods);

        Map<String, AllocateApplyOrderQueryGoodsListDateilResponse> goodsMap =
                getGoodsMap(goodsListDateilResponse);
        log.info("goodFilters after {}", JSONObject.toJSONString(goodsMap));
        //根据id分组
        Map<String, List<AllocateApplyOrderImportRequest>> listGroup = list.stream().collect(Collectors.groupingBy(AllocateApplyOrderImportRequest::getOrderId));

        Result<List<com.epoch.app.otsplatformenhance.sdo.OrganizationSDO>> loginEmployeeSaleOrganization = null;
        try{
             loginEmployeeSaleOrganization = otsPlatformEnhanceService.getLoginEmployeeSaleOrganization();
        }catch (Throwable e){
            for (Map.Entry<String, List<AllocateApplyOrderImportRequest>> entry : listGroup.entrySet()) {
                List<AllocateApplyOrderImportRequest> value = entry.getValue();
                if (CollectionUtils.isNotEmpty(value)){
                    for (AllocateApplyOrderImportRequest allocateApplyOrderImportRequest : value) {
                        allocateApplyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-156",null).getDisplayErrorMessage());
                    }
                }
            }
            log.error("AllocateApplyOrderWriteServiceImpl.allocateApplyOrderImport.getLoginEmployeeSaleOrganizationError:{},request:{}",
                    e.getMessage(),JSON.toJSONString(request));
            return Result.success(request);
//            throw new FacadeException("OTS-03-001-00-15-156");
        }
        //遍历主单map
        for (Map.Entry<String, List<AllocateApplyOrderImportRequest>> entry : listGroup.entrySet()) {
            try {
                //方法变更了 此处增加了一个是否业务员参数
                allocateApplyOrderWriteServiceImpl.createAllocateApplyOrder(entry,
                        scItemGroupMap,
                        goodFilters,
                        goods,
                        goodsMap,
                        goodsListDateilResponse,
                        organizationSDO,
                        isSalesMan,
                        loginEmployeeSaleOrganization);
            } catch (Throwable e) {
                if ( e != null &&  e.getMessage() != null && e.getMessage().contains("各种id不应为空")){
                    for (Map.Entry<String, List<AllocateApplyOrderImportRequest>> listEntry : listGroup.entrySet()) {
                        for (AllocateApplyOrderImportRequest importRequest : listEntry.getValue()) {
                            if (StringUtils.isBlank(importRequest.getErrorMessage())){
                                importRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-156",null).getDisplayErrorMessage());
                            }
                        }
                    }
                }
                log.error("AllocateApplyOrderWriteServiceImpl.allocateApplyOrderImport exception:", e);
                Result.success(request);
//                throw e;
            }


        }
        log.info("AllocateApplyOrderWriteServiceImpl.allocateApplyOrderImport,result:{}", JSON.toJSONString(request));
        return Result.success(request);
    }

    @Transactional(rollbackFor = Exception.class)
    public void createAllocateApplyOrder(Map.Entry<String, List<AllocateApplyOrderImportRequest>> entry,
                                         Map<String, String> scItemGroupMap,
                                         List<AllocateApplyOrderImportRequest> goodFilters,
                                         List<String> goods,
                                         Map<String, AllocateApplyOrderQueryGoodsListDateilResponse> goodsMap,
                                         List<AllocateApplyOrderQueryGoodsListDateilResponse> goodsListDateilResponse,
                                         Long organizationSDO) {
        //主单实体
        AllocateApplyOrderCreateDTO allocateApplyOrderCreateDTO = new AllocateApplyOrderCreateDTO();
        //主单保存工程返回实体
        AllocateApplyOrderDetailDTO allocateApplyOrderDetailDTOResult = new AllocateApplyOrderDetailDTO();
        //子单list
        List<AllocateApplyOrderImportRequest> enterList = entry.getValue();
        if (enterList.size() > 100) {
            for (AllocateApplyOrderImportRequest applyOrderImportRequest : enterList) {
                applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-063", null).getDisplayErrorMessage());
            }
            return;
        }
        //主单是否装配标记
        boolean mainOrderIsBuilder = false;
        //行号
        int lineNO = 1;
        //子单主题，包含主单信息
        AllocateApplyOrderUpdateDTO allocateApplyOrderUpdateDTO = new AllocateApplyOrderUpdateDTO();
        //子单list
        List<AllocateApplyOrderDetailCreateDTO> subList = Lists.newArrayList();
        //遍历子单list
        QueryCustomerAddressDTO customerAddress = null;
        for (AllocateApplyOrderImportRequest applyOrderImportRequest : enterList) {
            applyOrderImportRequest.setApplyOrgId(organizationSDO);
            Boolean checkParameterResult = checkParameter(applyOrderImportRequest);
            if (!checkParameterResult) {
                log.error("checkParameterResult fail {}", JSONObject.toJSONString(applyOrderImportRequest));
                continue;
            }
            //日期格式校验
            String gmtCreateString = applyOrderImportRequest.getGmtCreate();
            if (StringUtils.isNotEmpty(gmtCreateString)) {
                if (!validationDateFormat(gmtCreateString)) {
                    log.error("checkGmtCreateString fail {}", JSONObject.toJSONString(applyOrderImportRequest));
                    applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-067", null).getDisplayErrorMessage());
                    continue;
                }
            }
            String expectedDeliveryTimeString = applyOrderImportRequest.getExpectedDeliveryTime();
            if (StringUtils.isNotEmpty(expectedDeliveryTimeString)) {
                if (!validationDateFormat(expectedDeliveryTimeString)) {
                    log.error("checkExpectedDeliveryTimeString fail {}", JSONObject.toJSONString(applyOrderImportRequest));
                    applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-074", null).getDisplayErrorMessage());
                    continue;
                }
            }
            //判断时间是否正确
            //单据日期
            if (Objects.nonNull(applyOrderImportRequest.getGmtCreate())){
                Date date = TimeUtil.parseYYYY_MM_dd(applyOrderImportRequest.getGmtCreate());
                if (!isDateError(date)){
                    applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-083", null).getDisplayErrorMessage());
                    continue;
                }
            }
            //期望交货日期
            if (Objects.nonNull(applyOrderImportRequest.getExpectedDeliveryTime())){
                Date date = TimeUtil.parseYYYY_MM_dd(applyOrderImportRequest.getExpectedDeliveryTime());
                if (!isDateError(date)){
                    applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-084", null).getDisplayErrorMessage());
                    continue;
                }
            }


            //设置默认值
//                    setDefaultParameter(applyOrderImportRequest);
            log.info("AllocateApplyOrderWriteServiceImpl.allocateApplyOrderImport.setDefaultParameter,result:{}", JSON.toJSONString(applyOrderImportRequest));
            //子单明细实体
            AllocateApplyOrderDetailCreateDTO subOrder = new AllocateApplyOrderDetailCreateDTO();
            //校验调拨类型
            if (!this.checkOrderType(applyOrderImportRequest.getType())) {
                log.error("checkOrderType fail {}", JSONObject.toJSONString(applyOrderImportRequest));
                applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-007", null).getDisplayErrorMessage());
                continue;
            }

            //校验是否直发客户
            if (!this.checkIsDTC(applyOrderImportRequest.getIsDTC())) {
                log.error("checkIsDTC fail {}", JSONObject.toJSONString(applyOrderImportRequest));
                applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-008", null).getDisplayErrorMessage());
                continue;
            }
            //直发客户对应调拨预报单类型对不对
            if (!TWO_STRING.equals(applyOrderImportRequest.getType()) && new Integer(1) == applyOrderImportRequest.getIsDTC()) {
                log.error("checkIsDTC else fail {}", JSONObject.toJSONString(applyOrderImportRequest));
                applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-056", null).getDisplayErrorMessage());
                continue;
            }
            //校验货品组值是否正确
            if (Objects.isNull(scItemGroupMap.get(applyOrderImportRequest.getGoodsGroup()))) {
                log.error("checkScItemGroupMap  fail {}", JSONObject.toJSONString(applyOrderImportRequest));
                applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-057", null).getDisplayErrorMessage());
                continue;
            }
            QueryCustomerAddressDTO customerAddressSDO = new QueryCustomerAddressDTO();

            //校验客户地址编码并返回实体,非直发客户不需要查询
            if (new Integer(1).equals(applyOrderImportRequest.getIsDTC())) {
                if (StringUtils.isEmpty(applyOrderImportRequest.getCustomerAddress())) {
                    log.error("checkCustomerAddress  fail {}", JSONObject.toJSONString(applyOrderImportRequest));
                    applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-058", null).getDisplayErrorMessage());
                    continue;
                }
                customerAddressSDO = this.checkCustomerAddress(applyOrderImportRequest.getCustomerAddress());
                if (customerAddressSDO != null){
                    customerAddress = customerAddressSDO;
                }
                if (Objects.isNull(customerAddressSDO)) {
                    log.error("checkCustomerAddressSDO  fail {}", JSONObject.toJSONString(applyOrderImportRequest));
                    applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-009", null).getDisplayErrorMessage());
                    continue;
                }
            }

            //校验分公司客户编码，当直接发客户时候才需要校验
            if (new Integer(1).equals(applyOrderImportRequest.getIsDTC())) {
                if (StringUtils.isEmpty(applyOrderImportRequest.getBranchCustomersCode())) {
                    log.error("checkBranchCustomersCode  fail {}", JSONObject.toJSONString(applyOrderImportRequest));
                    applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-073", null).getDisplayErrorMessage());
                    continue;
                }
                BranchCustomersDTO branchCustomers =
                        this.checkCustomerCode(applyOrderImportRequest.getBranchCustomersCode());
                if (Objects.isNull(branchCustomers)) {
                    log.error("checkBranchCustomersCode else  fail {}", JSONObject.toJSONString(applyOrderImportRequest));
                    applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-024", null).getDisplayErrorMessage());
                    continue;
                }
            }
            if (StringUtils.isEmpty(applyOrderImportRequest.getDeliveryWarehouseCode())) {
                log.error("checkDeliveryWarehouseCode else  fail {}", JSONObject.toJSONString(applyOrderImportRequest));
                applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-066", null).getDisplayErrorMessage());
                continue;
            }
            //校验收发货仓编码
            WarehouseBaseInfo warehouseInfo = checkWarehouse(
                    applyOrderImportRequest.getReceiveWarehouseCode(),
                    applyOrderImportRequest.getDeliveryWarehouseCode(),
                    applyOrderImportRequest.getType(), applyOrderImportRequest.getIsDTC());
            if (!new Integer(1).equals(applyOrderImportRequest.getIsDTC())) {
                if (Objects.isNull(warehouseInfo)
                        || StringUtils.isBlank(warehouseInfo.getReceiveWarehouseId())) {
                    log.error("checkWarehouseInfo  fail {}", JSONObject.toJSONString(applyOrderImportRequest));
                    applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-064", null).getDisplayErrorMessage());
                    continue;
                }
            }
            if (new Integer(1).equals(applyOrderImportRequest.getIsDTC()) && Objects.isNull(warehouseInfo) ||
                    StringUtils.isBlank(warehouseInfo.getDeliveryWarehouseId())) {
                log.error("checkDeliveryWarehouseId  fail {}", JSONObject.toJSONString(applyOrderImportRequest));
                applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-065", null).getDisplayErrorMessage());
                continue;
            }
            //校验订单备注长度
            if (Objects.nonNull(applyOrderImportRequest.getRemark()) && applyOrderImportRequest.getRemark().length() > 255) {
                log.error("checkRemark  fail {}", JSONObject.toJSONString(applyOrderImportRequest));
                applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-059", null).getDisplayErrorMessage());
                continue;
            }

            //校验货品编码并返回实体
            log.info("goodsMap pre result {}", JSONObject.toJSONString(applyOrderImportRequest));
            AllocateApplyOrderQueryGoodsListDateilResponse goodsObject = goodsMap.get(applyOrderImportRequest.getScItemId());
            log.info("goodsMap result {}", JSONObject.toJSONString(applyOrderImportRequest));
            log.info("goodsMap map result | " + JSONObject.toJSONString(applyOrderImportRequest) + " | "
                    + JSONObject.toJSONString(goodsObject));
            if (Objects.isNull(goodsObject)) {
                log.info("checkGoodsObject fail | " + JSONObject.toJSONString(applyOrderImportRequest) + " | goodsMap | "
                        + JSONObject.toJSONString(goodsMap) + "| goodsListDateilResponse | "
                        + JSONObject.toJSONString(goodsListDateilResponse) + " | goodFilters | "
                        + JSONObject.toJSONString(goodFilters) + "| goods |" + JSONObject.toJSONString(goods));
                applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-010", null).getDisplayErrorMessage());
                continue;
            }

            //提报量
            if (Objects.nonNull(applyOrderImportRequest.getApplyQuantity()) && applyOrderImportRequest.getApplyQuantity() < new Integer(0)) {
                log.error("checkApplyQuantity  fail {}", JSONObject.toJSONString(applyOrderImportRequest));
                applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-060", null).getDisplayErrorMessage());
                continue;
            }
            //结算金额
            if (AllocateOrderTypeEnum.CROSS_COMPANY.getType().equals(applyOrderImportRequest.getType())) {
                if (Objects.nonNull(applyOrderImportRequest.getExchangeAmt()) && applyOrderImportRequest.getExchangeAmt().compareTo(new BigDecimal(0)) == -1) {
                    log.error("checkExchangeAmt  fail {}", JSONObject.toJSONString(applyOrderImportRequest));
                    applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-061", null).getDisplayErrorMessage());
                    continue;
                }
            }
            //校验行备注长度
            if (Objects.nonNull(applyOrderImportRequest.getLineRemark()) && applyOrderImportRequest.getLineRemark().length() > 300) {
                log.error("checkLineRemark  fail {}", JSONObject.toJSONString(applyOrderImportRequest));
                applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-062", null).getDisplayErrorMessage());
                continue;
            }
            //提报量
            if (Objects.nonNull(applyOrderImportRequest.getApplyQuantity()) && applyOrderImportRequest.getApplyQuantity() < new Integer(0)) {
                log.error("checkApplyQuantity  fail {}", JSONObject.toJSONString(applyOrderImportRequest));
                applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-060", null).getDisplayErrorMessage());
                continue;
            }
            //结算金额
            if (AllocateOrderTypeEnum.CROSS_COMPANY.getType().equals(applyOrderImportRequest.getType())) {

                if (Objects.nonNull(applyOrderImportRequest.getExchangeAmt()) && applyOrderImportRequest.getExchangeAmt().compareTo(new BigDecimal(0)) == -1) {
                    log.error("checkExchangeAmt  fail {}", JSONObject.toJSONString(applyOrderImportRequest));
                    applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-061", null).getDisplayErrorMessage());
                    continue;
                }
            }
            //校验行备注长度
            if (Objects.nonNull(applyOrderImportRequest.getLineRemark()) && applyOrderImportRequest.getLineRemark().length() > 300) {
                log.error("checkLineRemark  fail {}", JSONObject.toJSONString(applyOrderImportRequest));
                applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-062", null).getDisplayErrorMessage());
                continue;
            }

            //装配主单信息，并保存
            if (!mainOrderIsBuilder) {
                //主单信息只装配一次
                createMainOrderBuilder(applyOrderImportRequest, allocateApplyOrderCreateDTO, warehouseInfo, customerAddressSDO);
                //先创建主单
                log.info("AllocateApplyOrderWriteServiceImpl.allocateApplyOrderImport.nykCreateAllocateApplyOrder,request:{}", JSON.toJSONString(allocateApplyOrderCreateDTO));
                allocateApplyOrderDetailDTOResult = nykCreateAllocateApplyOrder(allocateApplyOrderCreateDTO).getResult();
                log.info("AllocateApplyOrderWriteServiceImpl.allocateApplyOrderImport.nykCreateAllocateApplyOrder,result:{}", JSON.toJSONString(allocateApplyOrderDetailDTOResult));

                if (Objects.isNull(allocateApplyOrderDetailDTOResult)) {
                    //主单创建失败
                    applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-014", null).getDisplayErrorMessage());
                    continue;
                }
                //根据返回的主单信息装配子单的主体信息
                createSubOrdersMainOrderInfoBuilder(allocateApplyOrderUpdateDTO,
                        applyOrderImportRequest, allocateApplyOrderDetailDTOResult, customerAddressSDO, warehouseInfo);
                //标记为已装配
                mainOrderIsBuilder = true;
            }

            //校验物料编码一个主单只允许有一个
            Boolean checkGoodCode = checkGoodCode(subList, applyOrderImportRequest.getScItemId());
            if (!checkGoodCode) {
                applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-049", null).getDisplayErrorMessage());
                continue;
            }

            //装配子单信息
            AllocateApplyOrderDetailCreateDTO subOrderBuilder = createSubOrderBuilder(subOrder,
                    applyOrderImportRequest, allocateApplyOrderDetailDTOResult.getId(), lineNO, goodsObject);

            subList.add(subOrderBuilder);

            lineNO++;
        }
        //建子弹
        if (CollectionUtils.isNotEmpty(subList)) {
            allocateApplyOrderUpdateDTO.setList(subList);
            log.info("AllocateApplyOrderWriteServiceImpl.allocateApplyOrderImport.updateAllocateApplyOrder,request:{}", JSON.toJSONString(allocateApplyOrderUpdateDTO));
            if (allocateApplyOrderUpdateDTO.getIsDTC() != null && allocateApplyOrderUpdateDTO.getIsDTC()){
                if (customerAddress != null){
                    allocateApplyOrderUpdateDTO.setCustomerAddress(customerAddress.getAddressCode());
                }
            }
            updateAllocateApplyOrder(allocateApplyOrderUpdateDTO);
        }
    }


    //2022.02.25 因为业务员导入需要特殊判断 所以我这里新复制方法, 每次外层循环就是一个主单,里面是子单
    @Transactional(rollbackFor = Exception.class)
    public void createAllocateApplyOrder(Map.Entry<String, List<AllocateApplyOrderImportRequest>> entry,
                                         Map<String, String> scItemGroupMap,
                                         List<AllocateApplyOrderImportRequest> goodFilters,
                                         List<String> goods,
                                         Map<String, AllocateApplyOrderQueryGoodsListDateilResponse> goodsMap,
                                         List<AllocateApplyOrderQueryGoodsListDateilResponse> goodsListDateilResponse,
                                         Long organizationSDO,
                                         boolean isSalesMan,
                                         Result<List<com.epoch.app.otsplatformenhance.sdo.OrganizationSDO>> loginEmployeeSaleOrganization) {
        //主单实体
        AllocateApplyOrderCreateDTO allocateApplyOrderCreateDTO = new AllocateApplyOrderCreateDTO();
        //主单保存工程返回实体
        AllocateApplyOrderDetailDTO allocateApplyOrderDetailDTOResult = new AllocateApplyOrderDetailDTO();
        //子单list
        List<AllocateApplyOrderImportRequest> enterList = entry.getValue();
        if (enterList.size() > 100) {
            for (AllocateApplyOrderImportRequest applyOrderImportRequest : enterList) {
                applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-063", null).getDisplayErrorMessage());
            }
            return;
        }
        //对导入数据同主单号的校验, 如果数据有重复的 那就给报错提示.
        int size = enterList.size();
        long typeCount = enterList.stream().map(AllocateApplyOrderImportRequest::getType).distinct().count();
        long isDTCCount = enterList.stream().map(AllocateApplyOrderImportRequest::getIsDTC).distinct().count();
        long goodsGroupCount = enterList.stream().map(AllocateApplyOrderImportRequest::getGoodsGroup).distinct().count();
        long receiveWareHouseCount = enterList.stream().map(AllocateApplyOrderImportRequest::getReceiveWarehouseCode).distinct().count();
        long deliveryWareHouseCount = enterList.stream().map(AllocateApplyOrderImportRequest::getDeliveryWarehouseCode).distinct().count();
        long customerAddressCount = enterList.stream().map(AllocateApplyOrderImportRequest::getCustomerAddress).distinct().count();
        long scItemIdCount = enterList.stream().map(AllocateApplyOrderImportRequest::getScItemId).distinct().count();
        long branchCustomerCodeCount = enterList.stream().map(AllocateApplyOrderImportRequest::getBranchCustomersCode).distinct().count();
        long gmtCreateCount = enterList.stream().map(AllocateApplyOrderImportRequest::getGmtCreate).distinct().count();
        long expectedDeliveryTimeCount = enterList.stream().map(AllocateApplyOrderImportRequest::getExpectedDeliveryTime).distinct().count();
        long shipMethodCount = enterList.stream().map(AllocateApplyOrderImportRequest::getShipMethod).distinct().count();
        long remarkCount = enterList.stream().map(AllocateApplyOrderImportRequest::getRemark).distinct().count();


        //同一单的重复性参数校验
        if (typeCount > 1){
            log.error("repeatCheckType fail:{}", JSONObject.toJSONString(enterList));
            for (AllocateApplyOrderImportRequest applyOrderImportRequest : enterList) {
                applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-134", null).getDisplayErrorMessage());
            }
            return;
        }
        if (isDTCCount > 1){
            log.error("repeatIsDTC fail:{}", JSONObject.toJSONString(enterList));
            for (AllocateApplyOrderImportRequest applyOrderImportRequest : enterList) {
                applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-135", null).getDisplayErrorMessage());
            }
            return;
        }
        if (goodsGroupCount > 1){
            log.error("repeatGoodsGroup fail:{}", JSONObject.toJSONString(enterList));
            for (AllocateApplyOrderImportRequest applyOrderImportRequest : enterList) {
                applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-136", null).getDisplayErrorMessage());
            }
            return;
        }
        if (receiveWareHouseCount > 1){
            log.error("repeatReceiveWareHouse fail:{}", JSONObject.toJSONString(enterList));
            for (AllocateApplyOrderImportRequest applyOrderImportRequest : enterList) {
                applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-137", null).getDisplayErrorMessage());
            }
            return;
        }
        if (deliveryWareHouseCount > 1){
            log.error("repeatDeliveryWareHouse fail:{}", JSONObject.toJSONString(enterList));
            for (AllocateApplyOrderImportRequest applyOrderImportRequest : enterList) {
                applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-138", null).getDisplayErrorMessage());
            }
            return;
        }
        if (customerAddressCount > 1){
            log.error("repeatCustomerAddress fail:{}", JSONObject.toJSONString(enterList));
            for (AllocateApplyOrderImportRequest applyOrderImportRequest : enterList) {
                applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-139", null).getDisplayErrorMessage());
            }
            return;
        }
        if (branchCustomerCodeCount > 1){
            log.error("repeatBranchCustomerCode fail:{}", JSONObject.toJSONString(enterList));
            for (AllocateApplyOrderImportRequest applyOrderImportRequest : enterList) {
                applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-140", null).getDisplayErrorMessage());
            }
            return;
        }
        if (scItemIdCount < size){
            log.error("repeatScItemId fail:{}", JSONObject.toJSONString(enterList));
            for (AllocateApplyOrderImportRequest applyOrderImportRequest : enterList) {
                applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-141", null).getDisplayErrorMessage());
            }
            return;
        }
        if (gmtCreateCount > 1){
            log.error("repeatGmtCreate fail:{}", JSONObject.toJSONString(enterList));
            for (AllocateApplyOrderImportRequest applyOrderImportRequest : enterList) {
                applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-142", null).getDisplayErrorMessage());
            }
            return;
        }
        if (expectedDeliveryTimeCount > 1){
            log.error("repeatExpectedDeliveryTime fail:{}", JSONObject.toJSONString(enterList));
            for (AllocateApplyOrderImportRequest applyOrderImportRequest : enterList) {
                applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-143", null).getDisplayErrorMessage());
            }
            return;
        }
        if (shipMethodCount > 1){
            log.error("repeatShipMethod fail:{}", JSONObject.toJSONString(enterList));
            for (AllocateApplyOrderImportRequest applyOrderImportRequest : enterList) {
                applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-144", null).getDisplayErrorMessage());
            }
            return;
        }
        if (remarkCount > 1){
            log.error("repeatRemark fail:{}", JSONObject.toJSONString(enterList));
            for (AllocateApplyOrderImportRequest applyOrderImportRequest : enterList) {
                applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-145", null).getDisplayErrorMessage());
            }
            return;
        }
        //主单是否装配标记
        boolean mainOrderIsBuilder = false;
        //行号
        int lineNO = 1;
        //子单主题，包含主单信息
        AllocateApplyOrderUpdateDTO allocateApplyOrderUpdateDTO = new AllocateApplyOrderUpdateDTO();
        //子单list
        List<AllocateApplyOrderDetailCreateDTO> subList = Lists.newArrayList();
        //遍历子单list
        QueryCustomerAddressDTO customerAddress = null;
        boolean success = true;
        for (AllocateApplyOrderImportRequest applyOrderImportRequest : enterList) {
            applyOrderImportRequest.setApplyOrgId(organizationSDO);
            Boolean checkParameterResult = checkParameter(applyOrderImportRequest);
            if (!checkParameterResult) {
                log.error("checkParameterResult fail {}", JSONObject.toJSONString(applyOrderImportRequest));
                success = false;
                continue;
            }
            //业务员的校验 业务员只能创建工厂直发的预报单
            //如果是业务员 且 (非工厂直发 || 调拨类型不是总部的)
            if (isSalesMan &&
                    (!Objects.equals(applyOrderImportRequest.getIsDTC(),1)
                            || !Objects.equals(applyOrderImportRequest.getType(), AllocateOrderTypeEnum.HEADQUARTER_SALES.getType()))){
                log.error("checkSalesMan fail {}", JSONObject.toJSONString(applyOrderImportRequest));
                applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-133", null).getDisplayErrorMessage());
                success =false;
                continue;
            }
            //日期格式校验
            String gmtCreateString = applyOrderImportRequest.getGmtCreate();
            if (StringUtils.isNotEmpty(gmtCreateString)) {
                if (!validationDateFormat(gmtCreateString)) {
                    log.error("checkGmtCreateString fail {}", JSONObject.toJSONString(applyOrderImportRequest));
                    applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-067", null).getDisplayErrorMessage());
                    success = false;
                    continue;
                }
            }
            String expectedDeliveryTimeString = applyOrderImportRequest.getExpectedDeliveryTime();
            if (StringUtils.isNotEmpty(expectedDeliveryTimeString)) {
                if (!validationDateFormat(expectedDeliveryTimeString)) {
                    log.error("checkExpectedDeliveryTimeString fail {}", JSONObject.toJSONString(applyOrderImportRequest));
                    applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-074", null).getDisplayErrorMessage());
                    success = false;
                    continue;
                }
            }
            //判断时间是否正确
            //单据日期
            if (Objects.nonNull(applyOrderImportRequest.getGmtCreate())){
                Date date = TimeUtil.parseYYYY_MM_dd(applyOrderImportRequest.getGmtCreate());
                if (!isDateError(date)){
                    applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-083", null).getDisplayErrorMessage());
                    success = false;
                    continue;
                }
            }
            //期望交货日期
            if (Objects.nonNull(applyOrderImportRequest.getExpectedDeliveryTime())){
                Date date = TimeUtil.parseYYYY_MM_dd(applyOrderImportRequest.getExpectedDeliveryTime());
                if (!isDateError(date)){
                    applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-084", null).getDisplayErrorMessage());
                    success = false;
                    continue;
                }
            }


            //设置默认值
//                    setDefaultParameter(applyOrderImportRequest);
            log.info("AllocateApplyOrderWriteServiceImpl.allocateApplyOrderImport.setDefaultParameter,result:{}", JSON.toJSONString(applyOrderImportRequest));
            //子单明细实体
            AllocateApplyOrderDetailCreateDTO subOrder = new AllocateApplyOrderDetailCreateDTO();
            //校验调拨类型
            if (!this.checkOrderType(applyOrderImportRequest.getType())) {
                log.error("checkOrderType fail {}", JSONObject.toJSONString(applyOrderImportRequest));
                applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-007", null).getDisplayErrorMessage());
                success = false;
                continue;
            }

            //校验是否直发客户
            if (!this.checkIsDTC(applyOrderImportRequest.getIsDTC())) {
                log.error("checkIsDTC fail {}", JSONObject.toJSONString(applyOrderImportRequest));
                applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-008", null).getDisplayErrorMessage());
                success = false;
                continue;
            }
            //直发客户对应调拨预报单类型对不对
            if (!TWO_STRING.equals(applyOrderImportRequest.getType()) && new Integer(1) == applyOrderImportRequest.getIsDTC()) {
                log.error("checkIsDTC else fail {}", JSONObject.toJSONString(applyOrderImportRequest));
                applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-056", null).getDisplayErrorMessage());
                success = false;
                continue;
            }
            //校验货品组值是否正确
            if (Objects.isNull(scItemGroupMap.get(applyOrderImportRequest.getGoodsGroup()))) {
                log.error("checkScItemGroupMap  fail {}", JSONObject.toJSONString(applyOrderImportRequest));
                applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-057", null).getDisplayErrorMessage());
                success = false;
                continue;
            }
            QueryCustomerAddressDTO customerAddressSDO = new QueryCustomerAddressDTO();

            //校验客户地址编码并返回实体,非直发客户不需要查询
            if (new Integer(1).equals(applyOrderImportRequest.getIsDTC())) {
                if (StringUtils.isEmpty(applyOrderImportRequest.getCustomerAddress())) {
                    log.error("checkCustomerAddress  fail {}", JSONObject.toJSONString(applyOrderImportRequest));
                    applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-058", null).getDisplayErrorMessage());
                    success = false;
                    continue;
                }
                customerAddressSDO = this.checkCustomerAddress(applyOrderImportRequest.getCustomerAddress());
                if (customerAddressSDO != null){
                    customerAddress = customerAddressSDO;
                }
                if (Objects.isNull(customerAddressSDO)) {
                    log.error("checkCustomerAddressSDO  fail {}", JSONObject.toJSONString(applyOrderImportRequest));
                    applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-009", null).getDisplayErrorMessage());
                    success = false;
                    continue;
                }
            }

            //校验分公司客户编码，当直接发客户时候才需要校验
            if (new Integer(1).equals(applyOrderImportRequest.getIsDTC())) {
                //2022.02.28变更 导入取消对分公司客户编码的非空校验
//                if (StringUtils.isEmpty(applyOrderImportRequest.getBranchCustomersCode())) {
//                    log.error("checkBranchCustomersCode  fail {}", JSONObject.toJSONString(applyOrderImportRequest));
//                    applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-073", null).getDisplayErrorMessage());
//                    continue;
//                }
                if (StringUtils.isNotBlank(applyOrderImportRequest.getBranchCustomersCode())){
                    BranchCustomersDTO branchCustomers =
                            this.checkCustomerCode(applyOrderImportRequest.getBranchCustomersCode());
                    if (Objects.isNull(branchCustomers)) {
                        log.error("checkBranchCustomersCode else  fail {}", JSONObject.toJSONString(applyOrderImportRequest));
                        applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-024", null).getDisplayErrorMessage());
                        success = false;
                        continue;
                    }
                }
            }
            if (StringUtils.isEmpty(applyOrderImportRequest.getDeliveryWarehouseCode())) {
                log.error("checkDeliveryWarehouseCode else  fail {}", JSONObject.toJSONString(applyOrderImportRequest));
                applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-066", null).getDisplayErrorMessage());
                success = false;
                continue;
            }
            //2022.04.01改动 多加了当前登录人组织
            //校验收发货仓编码
            WarehouseBaseInfo warehouseInfo = checkWarehouse(
                    applyOrderImportRequest.getReceiveWarehouseCode(),
                    applyOrderImportRequest.getDeliveryWarehouseCode(),
                    applyOrderImportRequest.getType(), applyOrderImportRequest.getIsDTC(),
                    loginEmployeeSaleOrganization);
            if (!new Integer(1).equals(applyOrderImportRequest.getIsDTC())) {
                if (Objects.isNull(warehouseInfo)
                        || StringUtils.isBlank(warehouseInfo.getReceiveWarehouseId())) {
                    log.error("checkWarehouseInfo  fail {}", JSONObject.toJSONString(applyOrderImportRequest));
                    applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-064", null).getDisplayErrorMessage());
                    success = false;
                    continue;
                }
            }
            if (new Integer(1).equals(applyOrderImportRequest.getIsDTC()) && Objects.isNull(warehouseInfo) ||
                    StringUtils.isBlank(warehouseInfo.getDeliveryWarehouseId())) {
                log.error("checkDeliveryWarehouseId  fail {}", JSONObject.toJSONString(applyOrderImportRequest));
                applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-065", null).getDisplayErrorMessage());
                success = false;
                continue;
            }
            //校验订单备注长度
            if (Objects.nonNull(applyOrderImportRequest.getRemark()) && applyOrderImportRequest.getRemark().length() > 255) {
                log.error("checkRemark  fail {}", JSONObject.toJSONString(applyOrderImportRequest));
                applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-059", null).getDisplayErrorMessage());
                success = false;
                continue;
            }

            //校验货品编码并返回实体
            log.info("goodsMap pre result {}", JSONObject.toJSONString(applyOrderImportRequest));
            //2022.05.19 货品编码有可能格式不对 提示下
            if (goodsMap == null || goodsMap.isEmpty()){
                applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-157",null).getDisplayErrorMessage());
                success =false;
                continue;
            }
            AllocateApplyOrderQueryGoodsListDateilResponse goodsObject = goodsMap.get(applyOrderImportRequest.getScItemId());
            log.info("goodsMap result {}", JSONObject.toJSONString(applyOrderImportRequest));
            log.info("goodsMap map result | " + JSONObject.toJSONString(applyOrderImportRequest) + " | "
                    + JSONObject.toJSONString(goodsObject));
            if (Objects.isNull(goodsObject)) {
                log.info("checkGoodsObject fail | " + JSONObject.toJSONString(applyOrderImportRequest) + " | goodsMap | "
                        + JSONObject.toJSONString(goodsMap) + "| goodsListDateilResponse | "
                        + JSONObject.toJSONString(goodsListDateilResponse) + " | goodFilters | "
                        + JSONObject.toJSONString(goodFilters) + "| goods |" + JSONObject.toJSONString(goods));
                applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-010", null).getDisplayErrorMessage());
                success = false;
                continue;
            }

            //提报量
            if (Objects.nonNull(applyOrderImportRequest.getApplyQuantity()) && applyOrderImportRequest.getApplyQuantity() < new Integer(0)) {
                log.error("checkApplyQuantity  fail {}", JSONObject.toJSONString(applyOrderImportRequest));
                applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-060", null).getDisplayErrorMessage());
                success = false;
                continue;
            }
            //结算金额
            if (AllocateOrderTypeEnum.CROSS_COMPANY.getType().equals(applyOrderImportRequest.getType())) {
                if (Objects.nonNull(applyOrderImportRequest.getExchangeAmt()) && applyOrderImportRequest.getExchangeAmt().compareTo(new BigDecimal(0)) == -1) {
                    log.error("checkExchangeAmt  fail {}", JSONObject.toJSONString(applyOrderImportRequest));
                    applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-061", null).getDisplayErrorMessage());
                    success = false;
                    continue;
                }
            }
            //校验行备注长度
            if (Objects.nonNull(applyOrderImportRequest.getLineRemark()) && applyOrderImportRequest.getLineRemark().length() > 300) {
                log.error("checkLineRemark  fail {}", JSONObject.toJSONString(applyOrderImportRequest));
                applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-062", null).getDisplayErrorMessage());
                success = false;
                continue;
            }
            //提报量
            if (Objects.nonNull(applyOrderImportRequest.getApplyQuantity()) && applyOrderImportRequest.getApplyQuantity() < new Integer(0)) {
                log.error("checkApplyQuantity  fail {}", JSONObject.toJSONString(applyOrderImportRequest));
                applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-060", null).getDisplayErrorMessage());
                success = false;
                continue;
            }
            //结算金额
            if (AllocateOrderTypeEnum.CROSS_COMPANY.getType().equals(applyOrderImportRequest.getType())) {

                if (Objects.nonNull(applyOrderImportRequest.getExchangeAmt()) && applyOrderImportRequest.getExchangeAmt().compareTo(new BigDecimal(0)) == -1) {
                    log.error("checkExchangeAmt  fail {}", JSONObject.toJSONString(applyOrderImportRequest));
                    applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-061", null).getDisplayErrorMessage());
                    success = false;
                    continue;
                }
            }
            //校验行备注长度
            if (Objects.nonNull(applyOrderImportRequest.getLineRemark()) && applyOrderImportRequest.getLineRemark().length() > 300) {
                log.error("checkLineRemark  fail {}", JSONObject.toJSONString(applyOrderImportRequest));
                applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-062", null).getDisplayErrorMessage());
                success = false;
                continue;
            }
            //校验物料编码一个主单只允许有一个
            Boolean checkGoodCode = checkGoodCode(subList, applyOrderImportRequest.getScItemId());
            if (!checkGoodCode) {
                applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-049", null).getDisplayErrorMessage());
                success = false;
                continue;
            }


            //装配主单信息，并保存
            if (!mainOrderIsBuilder) {
                //主单信息只装配一次
                createMainOrderBuilder(applyOrderImportRequest, allocateApplyOrderCreateDTO, warehouseInfo, customerAddressSDO);
                //先创建主单
                log.info("AllocateApplyOrderWriteServiceImpl.allocateApplyOrderImport.nykCreateAllocateApplyOrder,request:{}", JSON.toJSONString(allocateApplyOrderCreateDTO));
                allocateApplyOrderDetailDTOResult = nykCreateAllocateApplyOrder(allocateApplyOrderCreateDTO).getResult();
                log.info("AllocateApplyOrderWriteServiceImpl.allocateApplyOrderImport.nykCreateAllocateApplyOrder,result:{}", JSON.toJSONString(allocateApplyOrderDetailDTOResult));

                if (Objects.isNull(allocateApplyOrderDetailDTOResult)) {
                    //主单创建失败
                    applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-014", null).getDisplayErrorMessage());
                    success = false;
                    continue;
                }
                //根据返回的主单信息装配子单的主体信息
                createSubOrdersMainOrderInfoBuilder(allocateApplyOrderUpdateDTO,
                        applyOrderImportRequest, allocateApplyOrderDetailDTOResult, customerAddressSDO, warehouseInfo);
                if (StringUtils.isNotBlank(applyOrderImportRequest.getErrorMessage())){
                    success = false;
                }
                //标记为已装配
                mainOrderIsBuilder = true;
            }
            //
            if (!success){
                if (StringUtils.isBlank(applyOrderImportRequest.getErrorMessage())){
                    applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-155", null).getDisplayErrorMessage());
                }
            }

//            //校验物料编码一个主单只允许有一个
//            Boolean checkGoodCode = checkGoodCode(subList, applyOrderImportRequest.getScItemId());
//            if (!checkGoodCode) {
//                applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-049", null).getDisplayErrorMessage());
//                continue;
//            }

            //装配子单信息
            AllocateApplyOrderDetailCreateDTO subOrderBuilder = createSubOrderBuilder(subOrder,
                    applyOrderImportRequest, allocateApplyOrderDetailDTOResult.getId(), lineNO, goodsObject);

            subList.add(subOrderBuilder);

            lineNO++;
        }
        //如果子单中有出现错误校验信息的 直接返回 主单暂时让创建 子单不能创建
        if (!success){
            for (AllocateApplyOrderImportRequest applyOrderImportRequest : enterList) {
                if (StringUtils.isBlank(applyOrderImportRequest.getErrorMessage())){
                    applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-155", null).getDisplayErrorMessage());
                }
            }
            return;
        }
        //建子弹
        if (CollectionUtils.isNotEmpty(subList)) {
            allocateApplyOrderUpdateDTO.setList(subList);
            log.info("AllocateApplyOrderWriteServiceImpl.allocateApplyOrderImport.updateAllocateApplyOrder,request:{}", JSON.toJSONString(allocateApplyOrderUpdateDTO));
            if (allocateApplyOrderUpdateDTO.getIsDTC() != null && allocateApplyOrderUpdateDTO.getIsDTC()){
                if (customerAddress != null){
                    allocateApplyOrderUpdateDTO.setCustomerAddress(customerAddress.getAddressCode());
                }
            }
            updateAllocateApplyOrder(allocateApplyOrderUpdateDTO);
        }
    }

    private HashMap<String, AllocateApplyOrderQueryGoodsListDateilResponse> getGoodsMap(
            List<AllocateApplyOrderQueryGoodsListDateilResponse> goodsListDateilResponse) {
        HashMap<String, AllocateApplyOrderQueryGoodsListDateilResponse> map = new HashMap<>();
        if (CollectionUtils.isEmpty(goodsListDateilResponse)) {
            return null;
        }
        for (AllocateApplyOrderQueryGoodsListDateilResponse res : goodsListDateilResponse) {
            if (Objects.isNull(map.get(res.getGoodsCode()))) {
                map.put(res.getGoodsCode(), res);
            }
        }
        return map;
    }

    private Boolean checkGoodCode(List<AllocateApplyOrderDetailCreateDTO> subList, String goodCode) {
        if (CollectionUtils.isEmpty(subList)) {
            return true;
        }
        List<String> goodsCodes = subList.stream().map(AllocateApplyOrderDetailCreateDTO::getScItemId).collect(Collectors.toList());
        if (!goodsCodes.contains(goodCode)) {
            return true;
        }
        log.info("重复");
        return false;
    }

    private Date getAfterThreeDays(){
        Calendar calendar = new GregorianCalendar();
        Date date = new Date();
        DateUtil.toString(date);
        calendar.getTime();
        DateUtils.formatDate(date);
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
        sdf.format(date);
        calendar.setTime(date);
        calendar.add(calendar.DATE, 3);
        return calendar.getTime();
    }

    public static void main(String[] args) throws ParseException {
        Calendar calendar = new GregorianCalendar();
        Date date = new Date();
        DateUtil.toString(date);
        calendar.getTime();
        DateUtils.formatDate(date);
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
        sdf.format(date);
        calendar.setTime(date);
        calendar.add(calendar.DATE, 3);
        calendar.getTime();
        DateUtil.parseStrToDate(sdf.format(date), DATE_FORMAT);
    }
//    private boolean validationDateFormat(String dateSting){

//    }

    public static boolean validationDateFormat(String str) {

        String pat = "^((\\d{2}(([02468][048])|([13579][26]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))?$";
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        try {
            format.setLenient(false);
            format.parse(str);
            //双重校验，日期格式成功后，在校验年份是不是yyyy
            Pattern p = Pattern.compile(pat);
            // 实例化Pattern类
            Matcher m = p.matcher(str);
            return m.matches();
        } catch (ParseException e) {
            return false;
        }
    }

    private void setDefaultParameter(AllocateApplyOrderCreateDTO allocateApplyOrderCreateDTO) {

        if (null == allocateApplyOrderCreateDTO.getOrderTime() || "".equals(allocateApplyOrderCreateDTO.getOrderTime())) {
            Date date = new Date();
            String currentTime = OtsDateUtils.formatDate(date, OtsDateUtils.TIME_FORMAT);
            if (Objects.nonNull(allocateApplyOrderCreateDTO.getType()) && 2 == allocateApplyOrderCreateDTO.getType()) {
                if (currentTime.compareTo(HEADQUARTERS_SALES_ALLOCATION_ORDER_TIME) > 0) {
                    Calendar calendar = Calendar.getInstance();
                    calendar.add(Calendar.DAY_OF_MONTH, 1);
                    date = calendar.getTime();
                }
            } else {
                if (currentTime.compareTo(orderTime) > 0) {
                    Calendar calendar = Calendar.getInstance();
                    calendar.add(Calendar.DAY_OF_MONTH, 1);
                    date = calendar.getTime();
                }
            }
            Date resultDate = OtsDateUtils.parseDate(OtsDateUtils.formatDate(date, OtsDateUtils.DATE_FORMAT), OtsDateUtils.DATE_FORMAT);
            allocateApplyOrderCreateDTO.setOrderTime(resultDate);
        } else {
            allocateApplyOrderCreateDTO.setOrderTime(allocateApplyOrderCreateDTO.getOrderTime());
        }
        //生效日期
        if (Objects.isNull(allocateApplyOrderCreateDTO.getTakeEffectTime()) || "".equals(allocateApplyOrderCreateDTO.getTakeEffectTime())) {
            allocateApplyOrderCreateDTO.setTakeEffectTime(allocateApplyOrderCreateDTO.getOrderTime());
        } else {
            allocateApplyOrderCreateDTO.setTakeEffectTime(allocateApplyOrderCreateDTO.getTakeEffectTime());
        }
        //失效日期
        if (Objects.isNull(allocateApplyOrderCreateDTO.getInvalidDate()) || "".equals(allocateApplyOrderCreateDTO.getInvalidDate())) {
            Calendar calendar = new GregorianCalendar();
            calendar.setTime(allocateApplyOrderCreateDTO.getTakeEffectTime());
            calendar.add(calendar.DATE, 1);
            allocateApplyOrderCreateDTO.setInvalidDate(calendar.getTime());
        } else {
            allocateApplyOrderCreateDTO.setInvalidDate(allocateApplyOrderCreateDTO.getInvalidDate());
        }
        if (Objects.isNull(allocateApplyOrderCreateDTO.getHopeDeliveryTime())) {
            allocateApplyOrderCreateDTO.setHopeDeliveryTime(getAfterThreeDays());
        }
    }

    @Override
    @FacadeInvoker(value = "sap回调预报单", errorCode = "OTS-03-001-00-15-028")
    public Result<Boolean> sapCallbackAllocateApplyOrder(SapCallbackAllocateApplyOrderEquest sapCallbackAllocateApplyOrderEquest) {
        log.info("AllocateApplyOrderWriteServiceImpl.sapCallbackAllocateApplyOrder,reques:{}", JSON.toJSONString(sapCallbackAllocateApplyOrderEquest));
        try(RedisLock lock = new RedisLock(BcOtsConstants.REDIS_CACHE_CODE(),"allocateApplyOrderUpdate_" + sapCallbackAllocateApplyOrderEquest.getOuterKey(),5 * 60 * 1000,10 * 60 * 1000)){
            if (!lock.lock()){
                return Result.fail("OTS-03-005-00-15-090","调拨单预报单回调更新获取锁失败");
            }
            /**
             * 判断预报单是否有值
             * 查找预报单
             * 修改预报单
             */
            if (Objects.nonNull(sapCallbackAllocateApplyOrderEquest) && Objects.nonNull(sapCallbackAllocateApplyOrderEquest.getInnerKey())) {
                QueryAllocateApplyOrderRequest queryAllocateApplyOrderRequest = new QueryAllocateApplyOrderRequest();
                queryAllocateApplyOrderRequest.setCode(sapCallbackAllocateApplyOrderEquest.getInnerKey());
                log.info("AllocateApplyOrderWriteServiceImpl.sapCallbackAllocateApplyOrder.queryAllocateApplyOrderByCode,oldReques:{}", JSON.toJSONString(queryAllocateApplyOrderRequest));
                Result<AllocateApplyOrderDetailDTO> allocateApplyOrderDetailDTOResult = allocateApplyOrderReadService.queryAllocateApplyOrderByCode(queryAllocateApplyOrderRequest);
                log.info("AllocateApplyOrderWriteServiceImpl.sapCallbackAllocateApplyOrder.queryAllocateApplyOrderByCode,oldResult:{}", JSON.toJSONString(allocateApplyOrderDetailDTOResult));
                //判断预报单是否有值
                if (Objects.nonNull(allocateApplyOrderDetailDTOResult) && Objects.nonNull(allocateApplyOrderDetailDTOResult.getResult())) {
                    AllocateApplyOrderDetailDTO allocateApplyOrderDetailDTO = allocateApplyOrderDetailDTOResult.getResult();
                    AllocateApplyOrderUpdateDTO allocateApplyOrderUpdateDTO = new AllocateApplyOrderUpdateDTO();
                    BeanUtils.copyProperties(allocateApplyOrderDetailDTO, allocateApplyOrderUpdateDTO);
                    List<AllocateApplyOrderGoodsDetailDTO> allocateApplyOrderGoodsDetailDTOS = allocateApplyOrderDetailDTO.getList();
                    List<AllocateApplyOrderDetailCreateDTO> allocateApplyOrderDetailCreateDTOS = new ArrayList<>();
                    for (AllocateApplyOrderGoodsDetailDTO allocateApplyOrderGoodsDetailDTO : allocateApplyOrderGoodsDetailDTOS) {
                        AllocateApplyOrderDetailCreateDTO allocateApplyOrderDetailCreateDTO = new AllocateApplyOrderDetailCreateDTO();
                        BeanUtils.copyProperties(allocateApplyOrderGoodsDetailDTO, allocateApplyOrderDetailCreateDTO);
                        allocateApplyOrderDetailCreateDTOS.add(allocateApplyOrderDetailCreateDTO);
                    }
                    allocateApplyOrderUpdateDTO.setList(allocateApplyOrderDetailCreateDTOS);
                    AllocateApplyOrderEntity allocateApplyOrderEntity;
                    //判断回调接口传来的状态修改预报单对应状态
                    if (sapCallbackAllocateApplyOrderEquest.getSuccess()) {
                        allocateApplyOrderUpdateDTO.setSapCallbackMessage(null);
                        allocateApplyOrderUpdateDTO.setOutAllocateApplyOrderId(sapCallbackAllocateApplyOrderEquest.getOuterKey());

                        log.info("AllocateApplyOrderWriteServiceImpl_sapCallbackAllocateApplyOrder_submit,code:{},data:{}", allocateApplyOrderUpdateDTO.getCode(), JSON.toJSONString(allocateApplyOrderUpdateDTO));
                        allocateApplyOrderEntity = AllocateApplyOrderFactory.submit(allocateApplyOrderUpdateDTO);
                        log.info("AllocateApplyOrderWriteServiceImpl_sapCallbackAllocateApplyOrder_submit,code:{},allocateApplyOrderEntityResultData:{}", allocateApplyOrderUpdateDTO.getCode(), JSON.toJSONString(allocateApplyOrderEntity));
                    } else {
                        if (Objects.equals(allocateApplyOrderUpdateDTO.getStatus(),AllocateApplyOrderStatusEnum.TO_BE_SUBMITTED.getCode())
                                || Objects.equals(allocateApplyOrderUpdateDTO.getStatus(),AllocateApplyOrderStatusEnum.DRAFT.getCode())){
                            allocateApplyOrderUpdateDTO.setSapCallbackMessage(sapCallbackAllocateApplyOrderEquest.getMessage());
                            allocateApplyOrderEntity = AllocateApplyOrderFactory.toBeSubmitted(allocateApplyOrderUpdateDTO);
                        }else {
                            log.info("AllocateApplyOrderWriteServiceImpl_sapCallbackAllocateApplyOrder_submit,errorCallBack,code:{},result:{}",allocateApplyOrderUpdateDTO.getCode(),JSON.toJSONString(allocateApplyOrderUpdateDTO));
                            return Result.success(true);
                        }
                    }
                    allocateApplyOrderEntity.update();
                    log.info("AllocateApplyOrderWriteServiceImpl.sapCallbackAllocateApplyOrder.queryAllocateApplyOrderByCode,newReques:{}", JSON.toJSONString(queryAllocateApplyOrderRequest));
                    Result<AllocateApplyOrderDetailDTO> allocateApplyOrderDetailDTOResultNew = allocateApplyOrderReadService.queryAllocateApplyOrderByCode(queryAllocateApplyOrderRequest);
                    log.info("AllocateApplyOrderWriteServiceImpl.sapCallbackAllocateApplyOrder.queryAllocateApplyOrderByCode,newResult:{}", JSON.toJSONString(allocateApplyOrderDetailDTOResultNew));
                }
            }
        }catch (Exception e){
            log.error("sapCallbackAllocateApplyOrderError",e);
            return Result.fail("OTS-03-005-00-15-091","调拨单预报单回调更新失败");
        }

        log.info("AllocateApplyOrderWriteServiceImpl.sapCallbackAllocateApplyOrder,result:{}", JSON.toJSONString(Result.success(true)));
        return Result.success(true);
    }

    private Boolean checkOrderType(Integer type) {
        if (Objects.isNull(type)) {
            return false;
        }
        if (new Integer(1) > type ||
                new Integer(4) < type) {
            return false;
        }
        return true;
    }

    private Boolean checkIsDTC(Integer isDTC) {
        if (Objects.isNull(isDTC)) {
            return false;
        }
        if (new Integer(0) > isDTC ||
                new Integer(1) < isDTC) {
            return false;
        }
        return true;
    }


    //装配主单信息
    private AllocateApplyOrderCreateDTO createMainOrderBuilder(AllocateApplyOrderImportRequest applyOrderImportRequest,
                                                               AllocateApplyOrderCreateDTO allocateApplyOrderCreateDTO,
                                                               WarehouseBaseInfo warehouseInfo,
                                                               QueryCustomerAddressDTO customerAddressSDO) {
        log.info("AllocateApplyOrderWriteServiceImpl.allocateApplyOrderImport.createMainOrderBuilder,applyOrderImportRequest:{},allocateApplyOrderCreateDTO:{},warehouseInfo:{},customerAddressSDO:{}",
                JSON.toJSONString(applyOrderImportRequest), JSON.toJSONString(allocateApplyOrderCreateDTO), JSON.toJSONString(warehouseInfo), JSON.toJSONString(customerAddressSDO));
        allocateApplyOrderCreateDTO.setType(Integer.valueOf(applyOrderImportRequest.getType()));

        allocateApplyOrderCreateDTO.setApplyOrgId(applyOrderImportRequest.getApplyOrgId());
        allocateApplyOrderCreateDTO.setGoodsGroup(11);


        if (!new Integer(1).equals(applyOrderImportRequest.getIsDTC())) {
            allocateApplyOrderCreateDTO.setReceiveWarehouseId(Integer.valueOf(warehouseInfo.getReceiveWarehouseId()));
            //验证收货仓类型 收货仓类型都是工厂类型逻辑仓库
            if (StringUtils.isNotEmpty(warehouseInfo.getReceiveWarehouseId())) {
                WmsSDO shipWmsSDO = InfoUtil.getWmsSDO(allocateApplyOrderCreateDTO.getReceiveWarehouseId().toString());
                if (Objects.nonNull(shipWmsSDO) && Objects.nonNull(shipWmsSDO.getWarehouseId())) {
                    allocateApplyOrderCreateDTO.setReceiveCargoZoneId(Integer.valueOf(shipWmsSDO.getWarehouseId()));
                    //收货仓不能是工厂类型仓库
                    if (StringUtils.isNotEmpty(shipWmsSDO.getType()) && WAREHOUSE_FACTORY_TYPE.equals(shipWmsSDO.getType())) {
                        applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-070", null).getDisplayErrorMessage());
                    }
                }
            }
        }
        allocateApplyOrderCreateDTO.setShipWarehouseId(warehouseInfo.getDeliveryWarehouseId());
        //验证发货仓类型 计划和总部销售 工厂类型逻辑仓 同公司和跨公司调拨 非工厂类型
        if (StringUtils.isNotEmpty(warehouseInfo.getDeliveryWarehouseId())) {
            WmsSDO shipWmsSDO = InfoUtil.getWmsSDO(allocateApplyOrderCreateDTO.getShipWarehouseId());
            if (Objects.nonNull(shipWmsSDO) && Objects.nonNull(shipWmsSDO.getWarehouseId())) {
                allocateApplyOrderCreateDTO.setShipCargoZoneId(shipWmsSDO.getWarehouseId());
                //判断调拨预报单类型，如果是计划和总部销售类型 判断仓库是不是工厂类型，如果不是报错
                String shipWmsType = "";
                if (StringUtils.isNotEmpty(shipWmsSDO.getType())) {
                    String[] shipWmsTypes = shipWmsSDO.getType().split("\\.");
                    shipWmsType = shipWmsTypes[0];
                }
                //如果是计划预报单 发货仓得是工厂直发
                if (DocumentTypeEnum.PLANNED_ALLOCATION.getCode().equals(allocateApplyOrderCreateDTO.getType().toString())) {
                    if (StringUtils.isNotEmpty(shipWmsSDO.getType()) && !WAREHOUSE_FACTORY_TYPE.equals(shipWmsType)) {
                        applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-071", null).getDisplayErrorMessage());
                    }
                }
                //如果是总部销售的
                if (DocumentTypeEnum.HEADQUARTERS_SALES_ALLOCATION.getCode().equals(allocateApplyOrderCreateDTO.getType().toString())){
                    //如果是工厂直发的,就要校验是不是工厂仓  2022.0215 新增 放出F1共享仓 新增F1-b
                    if (Objects.equals(1,applyOrderImportRequest.getIsDTC())){
//                        if (StringUtils.isNotEmpty(shipWmsSDO.getType()) && !WAREHOUSE_FACTORY_TYPE.equals(shipWmsType)) {
                        if (StringUtils.isNotEmpty(shipWmsSDO.getType()) && !WAREHOUSE_FACTORY_TYPE.equals(shipWmsType) && !WAREHOUSE_SHARED_TYPE.equals(shipWmsType)) {
//                            applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-071", null).getDisplayErrorMessage());
                            applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-089", null).getDisplayErrorMessage());
                        }
                    }else {
                        //非工厂直发的 就不校验了.
                        if (StringUtils.isNotEmpty(shipWmsSDO.getType()) &&
                                !WAREHOUSE_FACTORY_TYPE.equals(shipWmsType) &&
                                !WAREHOUSE_SHARED_TYPE.equals(shipWmsType)){
//                            throw new FacadeException("OTS-03-001-00-15-089");
                            applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-089", null).getDisplayErrorMessage());
                        }
                    }
                }
                //判断调拨预报单类型，如果是计划和总部销售类型 判断仓库是不是非工厂类型，如果不是报错
                if (DocumentTypeEnum.SAME_COMPANY_ALLOCATION.getCode().equals(allocateApplyOrderCreateDTO.getType().toString())
                        || DocumentTypeEnum.CROSS_COMPANY_BORROW_GOODS_ALLOCATION.getCode().equals(allocateApplyOrderCreateDTO.getType().toString())) {
                    if (StringUtils.isNotEmpty(shipWmsSDO.getType()) && WAREHOUSE_FACTORY_TYPE.equals(shipWmsType)) {
                        applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-072", null).getDisplayErrorMessage());
//                        throw new FacadeException("OTS-03-001-00-15-072");
                    }
                }
            }
        }

        if (new Integer(1).equals(applyOrderImportRequest.getIsDTC())) {
            allocateApplyOrderCreateDTO.setCustomerAddress(customerAddressSDO.getAddressCode());
            allocateApplyOrderCreateDTO.setCustomer(customerAddressSDO.getCustomerCode());
            allocateApplyOrderCreateDTO.setCustomerAddressId(customerAddressSDO.getId());
        }
        allocateApplyOrderCreateDTO.setIsDTC(new Integer(1).equals(applyOrderImportRequest.getIsDTC()) ? true : false);
        allocateApplyOrderCreateDTO.setSapDeliveryBPCode(warehouseInfo.getSapDeliveryBPCode());
        allocateApplyOrderCreateDTO.setSapSalesBPCode(warehouseInfo.getSapSalesBPCode());
        allocateApplyOrderCreateDTO.setSapInternalDeliveryBPCode(warehouseInfo.getSapInternalDeliveryBPCode());
        allocateApplyOrderCreateDTO.setSapInternalSalesBPCode(warehouseInfo.getSapInternalSalesBPCode());
        allocateApplyOrderCreateDTO.setRemark(applyOrderImportRequest.getRemark());
        if (StringUtils.isNotEmpty(applyOrderImportRequest.getExpectedDeliveryTime())) {
            allocateApplyOrderCreateDTO.setHopeDeliveryTime(TimeUtil.parseYYYY_MM_dd(applyOrderImportRequest.getExpectedDeliveryTime()));
        }
        if (new Integer(1).equals(applyOrderImportRequest.getIsDTC())) {
            allocateApplyOrderCreateDTO.setBranchCustomersCode(applyOrderImportRequest.getBranchCustomersCode());
        }
        //日期默认值
        setDefaultParameter(allocateApplyOrderCreateDTO);
        //默认运输方式01
        allocateApplyOrderCreateDTO.setShipMethod(
                (StringUtils.isNotBlank(applyOrderImportRequest.getShipMethod()))?
                        applyOrderImportRequest.getShipMethod():
                STRING_ONE);
        log.info("AllocateApplyOrderWriteServiceImpl.allocateApplyOrderImport.createMainOrderBuilder,result:{}", JSON.toJSONString(allocateApplyOrderCreateDTO));
        return allocateApplyOrderCreateDTO;
    }


    private Date getDate(String date) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(DATE_FORMAT);
        Date d = null;
        try {
            if (StringUtils.isNotEmpty(date)) {
                d = simpleDateFormat.parse(date);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return d;
    }

    private AllocateApplyOrderUpdateDTO createSubOrdersMainOrderInfoBuilder(AllocateApplyOrderUpdateDTO allocateApplyOrderUpdateDTO,
                                                                            AllocateApplyOrderImportRequest applyOrderImportRequest,
                                                                            AllocateApplyOrderDetailDTO allocateApplyOrderDetailDTO,
                                                                            QueryCustomerAddressDTO customerAddressSDO,
                                                                            WarehouseBaseInfo warehouseInfo) {
        log.info("AllocateApplyOrderWriteServiceImpl.allocateApplyOrderImport.createSubOrdersMainOrderInfoBuilder,allocateApplyOrderUpdateDTO:{},applyOrderImportRequest:{},allocateApplyOrderDetailDTO:{},customerAddressSDO:{},warehouseInfo:{}"
                , JSON.toJSONString(allocateApplyOrderUpdateDTO), JSON.toJSONString(applyOrderImportRequest), JSON.toJSONString(allocateApplyOrderDetailDTO), JSON.toJSONString(customerAddressSDO), JSON.toJSONString(warehouseInfo));
        allocateApplyOrderUpdateDTO.setId(allocateApplyOrderDetailDTO.getId());
        allocateApplyOrderUpdateDTO.setType(String.valueOf(applyOrderImportRequest.getType()));
        allocateApplyOrderUpdateDTO.setCode(allocateApplyOrderDetailDTO.getCode());
        allocateApplyOrderUpdateDTO.setHopeDeliveryTime(getDate(allocateApplyOrderDetailDTO.getHopeDeliveryTime()));
        allocateApplyOrderUpdateDTO.setTakeEffectTime(getDate(allocateApplyOrderDetailDTO.getTakeEffectTime()));
//        allocateApplyOrderUpdateDTO.setOrderTime(allocateApplyOrderDetailDTO.getOrderTime());
        if (!new Integer(1).equals(applyOrderImportRequest.getIsDTC())) {
            allocateApplyOrderUpdateDTO.setReceiveWarehouseId(Integer.valueOf(warehouseInfo.getReceiveWarehouseId()));
        }
//        allocateApplyOrderUpdateDTO.setReceiveCargoZoneId(678);
        allocateApplyOrderUpdateDTO.setStatus(1);
        allocateApplyOrderUpdateDTO.setCustomer(applyOrderImportRequest.getCustomerAddressName());
        allocateApplyOrderUpdateDTO.setCustomerAddress(applyOrderImportRequest.getCustomerAddress());
//        allocateApplyOrderUpdateDTO.setMonthPlan(allocateApplyOrderDetailDTO.getm);
//        allocateApplyOrderUpdateDTO.setTenDays(allocateApplyOrderDetailDTO.gette);
        allocateApplyOrderUpdateDTO.setRemark(applyOrderImportRequest.getRemark());
        allocateApplyOrderUpdateDTO.setShipWarehouseId(warehouseInfo.getDeliveryWarehouseId());
//        allocateApplyOrderUpdateDTO.setShipCargoZoneId("795");
//        allocateApplyOrderUpdateDTO.setInvalidDate(applyOrderImportRequest.geti);
        allocateApplyOrderUpdateDTO.setShipMethod(allocateApplyOrderDetailDTO.getShipMethod());
        allocateApplyOrderUpdateDTO.setSapRefPoNo(allocateApplyOrderDetailDTO.getSapRefPoNo());
        allocateApplyOrderUpdateDTO.setSapCostCenter(allocateApplyOrderDetailDTO.getSapCostCenter());
        allocateApplyOrderUpdateDTO.setSapSalesBPCode(allocateApplyOrderDetailDTO.getSapSalesBPCode());
        allocateApplyOrderUpdateDTO.setSapInternalDeliveryBPCode(allocateApplyOrderDetailDTO.getSapInternalDeliveryBPCode());
        allocateApplyOrderUpdateDTO.setSapInternalSalesBPCode(allocateApplyOrderDetailDTO.getSapInternalSalesBPCode());
//        allocateApplyOrderUpdateDTO.setRecepitWarehouseAddress(allocateApplyOrderDetailDTO.getRece);
//        allocateApplyOrderUpdateDTO.setCustomerAddressDetail(customerAddressSDO);
        allocateApplyOrderUpdateDTO.setIsDTC(new Integer(1).equals(applyOrderImportRequest.getIsDTC()) ? true : false);
        allocateApplyOrderUpdateDTO.setGoodsGroup(ELEVEN_STRING);
//        allocateApplyOrderUpdateDTO.setDeliveryFactoryCode();
//        allocateApplyOrderUpdateDTO.setDeliveryInventoryCode();
//        allocateApplyOrderUpdateDTO.setShipWarehouseType();
        allocateApplyOrderUpdateDTO.setGmtCreate(new Date());
        log.info("AllocateApplyOrderWriteServiceImpl.allocateApplyOrderImport.createSubOrdersMainOrderInfoBuilder,result:{}", JSON.toJSONString(allocateApplyOrderUpdateDTO));
        return allocateApplyOrderUpdateDTO;
    }

    //装配子单信息
    private AllocateApplyOrderDetailCreateDTO createSubOrderBuilder(AllocateApplyOrderDetailCreateDTO subOrder,
                                                                    AllocateApplyOrderImportRequest applyOrderImportRequest,
                                                                    Long mainOrderId,
                                                                    int lineNo,
                                                                    AllocateApplyOrderQueryGoodsListDateilResponse goodsObject) {
        log.info("AllocateApplyOrderWriteServiceImpl.allocateApplyOrderImport.createSubOrderBuilder,subOrder:{},applyOrderImportRequest:{},mainOrderId:{},lineNo:{},goodsObject:{}"
                , JSON.toJSONString(subOrder), JSON.toJSONString(applyOrderImportRequest), JSON.toJSONString(mainOrderId), JSON.toJSONString(lineNo), JSON.toJSONString(goodsObject));
        subOrder.setAllocateApplyOrderId(Integer.valueOf(mainOrderId + NULL_STRING));
        subOrder.setLineNo(lineNo);
        subOrder.setTitle(goodsObject.getGoodsName());
        subOrder.setScItemId(applyOrderImportRequest.getScItemId());
        subOrder.setGoodsId(goodsObject.getId());
        subOrder.setApplyQuantity(applyOrderImportRequest.getApplyQuantity());
        subOrder.setProductionTime(applyOrderImportRequest.getProductDate());
//        subOrder.setReplyQuantity(goodsObject.ge);
//        subOrder.setDeliverQuantity(goodsObject.);
//        subOrder.setProductionTime(goodsObject.getp);
//        subOrder.setStatus(goodsObject.get);
//        subOrder.setIsClosed(goodsObject.getis);
        subOrder.setUom(goodsObject.getBaseUnitCode());
        subOrder.setRemark(applyOrderImportRequest.getLineRemark());
//        subOrder.setReturnGood();
        //
        subOrder.setUnitPrice(goodsObject.getCIFPrice());
//        subOrder.setSubtotalMoney();
//        subOrder.setIsClosed();
        if (Objects.nonNull(applyOrderImportRequest.getExchangeAmt())) {
            subOrder.setExchangeAmt(applyOrderImportRequest.getExchangeAmt().setScale(2, BigDecimal.ROUND_HALF_UP));
        }
        log.info("AllocateApplyOrderWriteServiceImpl.allocateApplyOrderImport.createSubOrderBuilder,result:{}", JSON.toJSONString(subOrder));
        return subOrder;
    }

    //校验客户地址编码
    private QueryCustomerAddressDTO checkCustomerAddress(String customerAddress) {
        QueryCustomerAddressDTO address = new QueryCustomerAddressDTO();
        //地址信息
        QueryCustomerAddressRequest queryCustomerAddressRequest = new QueryCustomerAddressRequest();
        queryCustomerAddressRequest.setId(customerAddress);
        Result<List<QueryCustomerAddressDTO>> listResult = allocateApplyOrderDropDownSelectionService.queryCustomerAddress(queryCustomerAddressRequest);
        log.info("创建调拨预报单查询客户地址信息返回参：" + JSONObject.toJSONString(listResult));
        if (Objects.isNull(listResult)) {
            return null;
        }
        if (CollectionUtils.isEmpty(listResult.getResult())) {
            return null;
        }
        List<QueryCustomerAddressDTO> addressList = listResult.getResult();
        if (CollectionUtils.isNotEmpty(addressList)){
            address = addressList.get(0);
        }
        return address;
    }

    private BranchCustomersDTO checkCustomerCode(String branchCustomersCode) {
        if (StringUtils.isEmpty(branchCustomersCode)) {
            return null;
        }
        QueryBranchCustomersRequest queryBranchCustomersRequest = new QueryBranchCustomersRequest();
        queryBranchCustomersRequest.setCode(branchCustomersCode);
        Result<List<BranchCustomersDTO>> customerAddressSDOResult = allocateApplyOrderDropDownSelectionService.queryBranchCustomers(queryBranchCustomersRequest);
        if (customerAddressSDOResult.getTotal() < 1 &&
                CollectionUtils.isEmpty(customerAddressSDOResult.getResult())) {
            log.error("checkCustomerAddress null method:" + JSON.toJSONString(customerAddressSDOResult));
            return null;
        }
        List<BranchCustomersDTO> SDO = customerAddressSDOResult.getResult();
        return SDO.get(0);
    }

    @Data
    class WarehouseBaseInfo {
        private String receiveWarehouseId;
        private String receiveWarehouseName;
        private String deliveryWarehouseId;
        private String deliveryWarehouseName;
        private String sapDeliveryBPCode;
        private String sapSalesBPCode;
        private String sapInternalDeliveryBPCode;
        private String sapInternalSalesBPCode;
    }

    /**
     * @param receiveWarehouseCode  收货仓
     * @param deliveryWarehouseCode 发货仓
     */
    private WarehouseBaseInfo checkWarehouse(String receiveWarehouseCode, String deliveryWarehouseCode, Integer type, Integer isDTC) {
        WarehouseBaseInfo warehouseBaseInfo = new WarehouseBaseInfo();

        DeliveryWarehouseChoiceDTO receiveWarehouse = new DeliveryWarehouseChoiceDTO();
        DeliveryWarehouseChoiceDTO deliveryWarehouse = new DeliveryWarehouseChoiceDTO();
        //不是直发客户单子，需要查找收货仓，接口带权限校验
        if (!new Integer(1).equals(isDTC)&&StringUtils.isNotEmpty(receiveWarehouseCode)) {
            QueryReceivingWarehouseByTypeRequest queryReceivingWarehouseByTypeRequest = new QueryReceivingWarehouseByTypeRequest();
            queryReceivingWarehouseByTypeRequest.setCode(receiveWarehouseCode);
            queryReceivingWarehouseByTypeRequest.setType(type.toString());
            Result<List<DeliveryWarehouseChoiceDTO>> receiveWarehouseRes = forecastWarehouseService.queryReceivingWarehouseByType(queryReceivingWarehouseByTypeRequest);
            //收货仓实体
            if (Objects.nonNull(receiveWarehouseRes)&&CollectionUtils.isNotEmpty(receiveWarehouseRes.getResult())) {
                receiveWarehouse = receiveWarehouseRes.getResult().get(0);
            }
        }
        //查找发货仓库，接口带权限校验
        if (StringUtils.isNotEmpty(deliveryWarehouseCode)) {
            QueryDeliveryWarehouseByTypeRequest batchDeliveryWarehouseByIdsRequest = new QueryDeliveryWarehouseByTypeRequest();
            batchDeliveryWarehouseByIdsRequest.setCode(deliveryWarehouseCode);
            batchDeliveryWarehouseByIdsRequest.setType(type.toString());
            Result<List<DeliveryWarehouseChoiceDTO>> deliveryWarehouseRes = forecastWarehouseService.queryDeliveryWarehouseByType(batchDeliveryWarehouseByIdsRequest);
            if (Objects.nonNull(deliveryWarehouseRes)&&CollectionUtils.isNotEmpty(deliveryWarehouseRes.getResult())) {
                deliveryWarehouse = deliveryWarehouseRes.getResult().get(0);
            }
        }
        //获取对应收发所需要的值
        warehouseBaseInfo.setDeliveryWarehouseId(deliveryWarehouse.getValue());
        if (!new Integer(1).equals(isDTC)) {
            warehouseBaseInfo.setReceiveWarehouseId(receiveWarehouse.getValue());
        }
        warehouseBaseInfo.setSapDeliveryBPCode(deliveryWarehouse.getSapDeliveryBPCode());
        warehouseBaseInfo.setSapSalesBPCode(deliveryWarehouse.getSapSaleBPCode());
        warehouseBaseInfo.setSapInternalDeliveryBPCode(deliveryWarehouse.getSapInternalDeliveryBPCode());
        warehouseBaseInfo.setSapInternalSalesBPCode(deliveryWarehouse.getSapInternalSalesBPCode());
        return warehouseBaseInfo;
    }

    /**
     * 把单签登录人信息统一一下
     * @param receiveWarehouseCode  收货仓
     * @param deliveryWarehouseCode 发货仓
     */
    private WarehouseBaseInfo checkWarehouse(String receiveWarehouseCode, String deliveryWarehouseCode, Integer type, Integer isDTC,
                                             Result<List<com.epoch.app.otsplatformenhance.sdo.OrganizationSDO>> loginEmployeeSaleOrganization) {
        WarehouseBaseInfo warehouseBaseInfo = new WarehouseBaseInfo();

        DeliveryWarehouseChoiceDTO receiveWarehouse = new DeliveryWarehouseChoiceDTO();
        DeliveryWarehouseChoiceDTO deliveryWarehouse = new DeliveryWarehouseChoiceDTO();
        //不是直发客户单子，需要查找收货仓，接口带权限校验
        if (!new Integer(1).equals(isDTC)&&StringUtils.isNotEmpty(receiveWarehouseCode)) {
            QueryReceivingWarehouseByTypeRequest queryReceivingWarehouseByTypeRequest = new QueryReceivingWarehouseByTypeRequest();
            queryReceivingWarehouseByTypeRequest.setCode(receiveWarehouseCode);
            queryReceivingWarehouseByTypeRequest.setType(type.toString());
//            Result<List<DeliveryWarehouseChoiceDTO>> receiveWarehouseRes = forecastWarehouseService.queryReceivingWarehouseByType(queryReceivingWarehouseByTypeRequest);
            Result<List<DeliveryWarehouseChoiceDTO>> receiveWarehouseRes = queryReceivingWarehouseByType(queryReceivingWarehouseByTypeRequest,loginEmployeeSaleOrganization);
            //收货仓实体
            if (Objects.nonNull(receiveWarehouseRes)&&CollectionUtils.isNotEmpty(receiveWarehouseRes.getResult())) {
                receiveWarehouse = receiveWarehouseRes.getResult().get(0);
            }
        }
        //查找发货仓库，接口带权限校验
        if (StringUtils.isNotEmpty(deliveryWarehouseCode)) {
            QueryDeliveryWarehouseByTypeRequest batchDeliveryWarehouseByIdsRequest = new QueryDeliveryWarehouseByTypeRequest();
            batchDeliveryWarehouseByIdsRequest.setCode(deliveryWarehouseCode);
            batchDeliveryWarehouseByIdsRequest.setType(type.toString());
//            Result<List<DeliveryWarehouseChoiceDTO>> deliveryWarehouseRes = forecastWarehouseService.queryDeliveryWarehouseByType(batchDeliveryWarehouseByIdsRequest);
            Result<List<DeliveryWarehouseChoiceDTO>> deliveryWarehouseRes = queryDeliveryWarehouseByType(batchDeliveryWarehouseByIdsRequest,loginEmployeeSaleOrganization);
            if (Objects.nonNull(deliveryWarehouseRes)&&CollectionUtils.isNotEmpty(deliveryWarehouseRes.getResult())) {
                deliveryWarehouse = deliveryWarehouseRes.getResult().get(0);
            }
        }
        //获取对应收发所需要的值
        warehouseBaseInfo.setDeliveryWarehouseId(deliveryWarehouse.getValue());
        if (!new Integer(1).equals(isDTC)) {
            warehouseBaseInfo.setReceiveWarehouseId(receiveWarehouse.getValue());
        }
        warehouseBaseInfo.setSapDeliveryBPCode(deliveryWarehouse.getSapDeliveryBPCode());
        warehouseBaseInfo.setSapSalesBPCode(deliveryWarehouse.getSapSaleBPCode());
        warehouseBaseInfo.setSapInternalDeliveryBPCode(deliveryWarehouse.getSapInternalDeliveryBPCode());
        warehouseBaseInfo.setSapInternalSalesBPCode(deliveryWarehouse.getSapInternalSalesBPCode());
        return warehouseBaseInfo;
    }

    //校验货品信息
    private List<AllocateApplyOrderQueryGoodsListDateilResponse> checkGoodsCode(List<String> scItemIds) {
        if (CollectionUtils.isEmpty(scItemIds)) {
            return null;
        }
        ApplyOrderQueryGoodsListRequest queryGoodsListUnifiedInventoryRequest
                = new ApplyOrderQueryGoodsListRequest();
        queryGoodsListUnifiedInventoryRequest.setCodes(scItemIds);
        Result<List<AllocateApplyOrderQueryGoodsListDateilResponse>> goodsListResult =
                allocateApplyOrderGoodsService.queryNotClassifiedGoodsList(queryGoodsListUnifiedInventoryRequest);
        log.info("checkGoodsCode method:" + JSON.toJSONString(goodsListResult));
        if (Objects.isNull(goodsListResult)) {
            return null;
        }
        return goodsListResult.getResult();
    }

    private void saveDocumentLog(AllocateApplyOrderDetailDTO oldValue, AllocateApplyOrderDetailDTO newValue, Integer operateType, Map<String, String> features) {
        try {
            LoginUser loginUser = epochLoginUserService.getLoginUser();
            if (Objects.nonNull(oldValue)) {
                oldValue.setList(null);
            }
            if (Objects.nonNull(newValue)) {
                newValue.setList(null);
            }
            OpLogModel<AllocateApplyOrderDetailDTO> opLogModel = OpLogModel.<AllocateApplyOrderDetailDTO>builder()
                    .oldValue(oldValue)
                    .newValue(newValue)
                    .moduleName(ModuleEnum.UNIFIED_INVENTORY.getModuleName())
                    .moduleId(ModuleEnum.UNIFIED_INVENTORY.getModuleId())
                    .operateType(operateType)
                    .operatorType(OperatorType.USER.getOperatorType())
                    .operatorId(loginUser.getEmpId())//操作人
                    .objectId(newValue.getId().toString())
                    .objectName(newValue.getCode())
                    .features(JSONObject.toJSONString(features))
                    .build();
            log.asyncMonitorObjectChangeV2(opLogModel);
        } catch (Throwable e) {
            log.error("saveDocumentLog exception:  ", e);
            // 日志不抛出去，防止中断主流程
        }
    }

    @Override
    @FacadeInvoker(value = "牛要客创建预报单", errorCode = "OTS-03-001-00-15-027")
    public Result<AllocateApplyOrderDetailDTO> nykCreateAllocateApplyOrder(
            AllocateApplyOrderCreateDTO allocateApplyOrderCreateDTO) {
        log.info("AllocateApplyOrderWriteServiceImpl, nykCreateAllocateApplyOrder,request:{}", JSON.toJSONString(allocateApplyOrderCreateDTO));
        //判断前端是否传总部渠道编码，传了取前端传的，没传给默认值，类型等于总部销售调拨给20，其余给90
        if (Objects.nonNull(allocateApplyOrderCreateDTO.getHeadquartersChannelCode())) {
            allocateApplyOrderCreateDTO.setHeadquartersChannelCode(allocateApplyOrderCreateDTO.getHeadquartersChannelCode());
        } else {
            //总部销售调拨
            if (DocumentTypeEnum.HEADQUARTERS_SALES_ALLOCATION.getCode().equals(allocateApplyOrderCreateDTO.getType().toString())) {
                allocateApplyOrderCreateDTO.setHeadquartersChannelCode(TWENTY_STRING);
            } else {
                allocateApplyOrderCreateDTO.setHeadquartersChannelCode(NINETY_STRING);
            }
        }
        allocateApplyOrderCreateDTO.setHeadquartersOrganizationCode(Objects.nonNull(allocateApplyOrderCreateDTO.getHeadquartersOrganizationCode()) ? allocateApplyOrderCreateDTO.getHeadquartersOrganizationCode() : ORG_SALES_ORGANIZATION_CODE);
        //获取收货仓档案信息 导入接口也调用牛要客创建这个接口，会传仓库档案编码，这里就不需要在查一遍
        if (Objects.nonNull(allocateApplyOrderCreateDTO.getReceiveWarehouseId()) && Objects.isNull(allocateApplyOrderCreateDTO.getReceiveCargoZoneId())) {
            WmsSDO shipWmsSDO = InfoUtil.getWmsSDO(allocateApplyOrderCreateDTO.getReceiveWarehouseId().toString());
            if (Objects.nonNull(shipWmsSDO) && Objects.nonNull(shipWmsSDO.getWarehouseId())) {
                allocateApplyOrderCreateDTO.setReceiveCargoZoneId(Integer.valueOf(shipWmsSDO.getWarehouseId()));
            }
        }
        //获取发货仓档案信息
        if (Objects.nonNull(allocateApplyOrderCreateDTO.getShipWarehouseId()) && Objects.isNull(allocateApplyOrderCreateDTO.getShipCargoZoneId())) {
            WmsSDO shipWmsSDO = InfoUtil.getWmsSDO(allocateApplyOrderCreateDTO.getShipWarehouseId());
            if (Objects.nonNull(shipWmsSDO) && Objects.nonNull(shipWmsSDO.getWarehouseId())) {
                allocateApplyOrderCreateDTO.setShipCargoZoneId(shipWmsSDO.getWarehouseId());
            }
        }

        //插入调拨预报单
        log.info("AllocateApplyOrderWriteServiceImpl, nykCreate,request:{}", JSON.toJSONString(allocateApplyOrderCreateDTO));
        AllocateApplyOrderEntity allocateApplyOrderEntity = AllocateApplyOrderFactory.nykCreate(allocateApplyOrderCreateDTO);
        String code = allocateApplyOrderEntity.nykCreate();
        log.info("AllocateApplyOrderWriteServiceImpl, nykCreate,result:{}", JSON.toJSONString(code));

        //查询调拨预报单
        QueryAllocateApplyOrderRequest queryAllocateApplyOrderRequest = new QueryAllocateApplyOrderRequest();
        queryAllocateApplyOrderRequest.setCode(code);
//        log.info("AllocateApplyOrderWriteServiceImpl，queryAllocateApplyOrderByCode,request:{}", JSON.toJSONString(queryAllocateApplyOrderRequest));
        AllocateApplyOrderResponse allocateApplyOrderResponse = allocateApplyOrderReadRepository.queryAllocateApplyOrderByCode(queryAllocateApplyOrderRequest.getCode());
        log.info("AllocateApplyOrderWriteServiceImpl, queryAllocateApplyOrderByCode, result:{}", JSON.toJSONString(allocateApplyOrderResponse));
        if (Objects.isNull(allocateApplyOrderResponse) && Objects.isNull(allocateApplyOrderResponse.getAllocateApplyOrderDetailDTO())) {
            return null;
        }
//        log.info("AllocateApplyOrderWriteServiceImpl, nykCreateAllocateApplyOrder, result:{}", JSON.toJSONString(Result.success(allocateApplyOrderResponse.getAllocateApplyOrderDetailDTO())));
        return Result.success(allocateApplyOrderResponse.getAllocateApplyOrderDetailDTO());
    }

    private Boolean checkParameter(AllocateApplyOrderImportRequest applyOrderImportRequest) {
        //基础数据校验，不管何种场景都时必填字段
        if (Objects.isNull(applyOrderImportRequest)) {
            return false;
        }
        if(StringUtils.isBlank(applyOrderImportRequest.getShipMethod())){
            applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-078", null).getDisplayErrorMessage());
            return false;
        }
        if(Objects.isNull(TransportModeEnum.of(applyOrderImportRequest.getShipMethod()))){
            applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-079", null).getDisplayErrorMessage());
            return false;
        }
        if (Objects.isNull(applyOrderImportRequest.getOrderId())) {
            applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-015", null).getDisplayErrorMessage());
            return false;
        }
        if (StringUtils.isBlank(applyOrderImportRequest.getGoodsGroup())) {
            applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-018", null).getDisplayErrorMessage());
            return false;
        }
        if (StringUtils.isBlank(applyOrderImportRequest.getScItemId())) {
            applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-022", null).getDisplayErrorMessage());
            return false;
        }
        if (Objects.isNull(applyOrderImportRequest.getApplyQuantity())) {
            applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-023", null).getDisplayErrorMessage());
            return false;
        }
        if (applyOrderImportRequest.getApplyQuantity() < 1) {
            applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-051", null).getDisplayErrorMessage());
            return false;
        }
        if (Objects.isNull(applyOrderImportRequest.getType())) {
            applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-039", null).getDisplayErrorMessage());
            return false;
        }
        if (Objects.isNull(applyOrderImportRequest.getIsDTC())) {
            applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-017", null).getDisplayErrorMessage());
            return false;
        }
        if (applyOrderImportRequest.getType() > 5 || applyOrderImportRequest.getType() < 1) {
            applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-040", null).getDisplayErrorMessage());
            return false;
        }
        /**
         * type!=2 isdtc必为0;
         *
         * 当调拨类型为总部销售调拨（type = 2）,判断是否直发客户字段是1还是0
         * 如果等于1 设置isdtc = 1 ，验证客户地址值是否正确（通过编码查找地址信息（使用pc端客户地址下拉选接口），获取地址编码和客户编码放主单对应字段中）
         * 发货仓也需要验证
         * 再验证分公司客户编码是否可以查到值
         * 如果等于0 按正常逻辑走
         * 如果为空数据不进行导入
         *
         *
         * 收发仓库保存时 获取对应仓库档案 保存调拨预报单对应字段中
         * 收发货仓验证查找时 使用pc端创建预报单收发货仓下拉选进行查找
         */
        if (new Integer(2).equals(applyOrderImportRequest.getType()) &&
                new Integer(1).equals(applyOrderImportRequest.getIsDTC())) {
            //type = 2, isDTC = 1, 总部销售调拨且为客户直发,收货仓可以为空，其余必须校验
            if (StringUtils.isNotBlank(applyOrderImportRequest.getReceiveWarehouseCode())) {
                applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-044", null).getDisplayErrorMessage());
                return false;
            }
            //2022.0302 去掉分公司客户的校验
//            if (StringUtils.isBlank(applyOrderImportRequest.getBranchCustomersCode())) {
//                applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-025", null).getDisplayErrorMessage());
//                return false;
//            }
            if (StringUtils.isBlank(applyOrderImportRequest.getCustomerAddress())) {
                applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-021", null).getDisplayErrorMessage());
                return false;
            }
        }
        if (!new Integer(2).equals(applyOrderImportRequest.getType()) &&
                !new Integer(0).equals(applyOrderImportRequest.getIsDTC())) {
            //type != 2, 且dts！= 0
            applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-041", null).getDisplayErrorMessage());
            return false;
        }
        if (!new Integer(2).equals(applyOrderImportRequest.getType()) &&
                new Integer(0).equals(applyOrderImportRequest.getIsDTC())) {
            //type != 2, 且dts = 0
            if (StringUtils.isNotBlank(applyOrderImportRequest.getCustomerAddress())) {
                applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-042", null).getDisplayErrorMessage());
                return false;
            }
            if (StringUtils.isNotBlank(applyOrderImportRequest.getBranchCustomersCode())) {
                applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-043", null).getDisplayErrorMessage());
                return false;
            }
        }
//        if(StringUtils.isBlank(applyOrderImportRequest.getReceiveWarehouseCode())){
//            applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-019", null).getDisplayErrorMessage());
//            return false;
//        }
//        if(StringUtils.isBlank(applyOrderImportRequest.getDeliveryWarehouseCode())){
//            applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-020", null).getDisplayErrorMessage());
//            return false;
//        }
        if (new Integer(0).equals(applyOrderImportRequest.getIsDTC())) {
            if (StringUtils.isBlank(applyOrderImportRequest.getReceiveWarehouseCode())) {
                applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-019", null).getDisplayErrorMessage());
                return false;
            }
        }
        if (!new Integer(4).equals(applyOrderImportRequest.getType())) {
            if (Objects.nonNull(applyOrderImportRequest.getExchangeAmt())) {
                applyOrderImportRequest.setErrorMessage(ErrorMessage.code("OTS-03-001-00-15-048", null).getDisplayErrorMessage());
                return false;
            }
        }
        return true;
    }


    @Override
    @FacadeInvoker(value = "sap创建调拨预报单", errorCode = "OTS-03-001-00-15-045")
    public Result<String> sapCreateAllocateApplyOrder(AllocateApplyOrderUpdateDTO allocateApplyOrderUpdateDTO) {
        log.info("AllocateApplyOrderWriteServiceImpl.sapCreateAllocateApplyOrder,request:{}", JSON.toJSONString(allocateApplyOrderUpdateDTO));
        AllocateApplyOrderCreateDTO allocateApplyOrderCreateDTO = new AllocateApplyOrderCreateDTO();
        //调拨预报单类型
        allocateApplyOrderCreateDTO.setType(Integer.valueOf(allocateApplyOrderUpdateDTO.getType()));
        //是否工厂直发
        allocateApplyOrderCreateDTO.setIsDTC(allocateApplyOrderUpdateDTO.getIsDTC());
        //提报组织
        allocateApplyOrderCreateDTO.setApplyOrgId(StringUtils.isBlank(allocateApplyOrderUpdateDTO.getApplyOrgId())?null: Long.valueOf(allocateApplyOrderUpdateDTO.getApplyOrgId()));
        //外部单据号
//        allocateApplyOrderCreateDTO.setOutAllocateApplyOrderId(mnSapIf007SDO.getOutAllocateApplyOrderId());
        //部门（产品组）
        allocateApplyOrderCreateDTO.setGoodsGroup(Integer.valueOf(allocateApplyOrderUpdateDTO.getGoodsGroup()));
        //单据日期
        allocateApplyOrderCreateDTO.setOrderTime(allocateApplyOrderUpdateDTO.getOrderTime());
        //有效起始时间
        allocateApplyOrderCreateDTO.setTakeEffectTime(allocateApplyOrderUpdateDTO.getTakeEffectTime());
        //报价有效至
        allocateApplyOrderCreateDTO.setInvalidDate(allocateApplyOrderUpdateDTO.getInvalidDate());
        // 预计交货时间
        allocateApplyOrderCreateDTO.setHopeDeliveryTime(allocateApplyOrderUpdateDTO.getHopeDeliveryTime());
        //发货仓库
        allocateApplyOrderCreateDTO.setShipWarehouseId(allocateApplyOrderUpdateDTO.getShipWarehouseId());
        //收货仓库
        allocateApplyOrderCreateDTO.setReceiveWarehouseId(allocateApplyOrderUpdateDTO.getReceiveWarehouseId());
        //装运条件  获取为空
        allocateApplyOrderCreateDTO.setShipMethod(allocateApplyOrderUpdateDTO.getShipMethod());
        //备注
        allocateApplyOrderCreateDTO.setRemark(allocateApplyOrderUpdateDTO.getRemark());

        //总部内部送达方编号 收货仓带出
        allocateApplyOrderCreateDTO.setSapInternalDeliveryBPCode(allocateApplyOrderUpdateDTO.getSapInternalDeliveryBPCode());
        //总部内部售达方编号 收货仓带出
        allocateApplyOrderCreateDTO.setSapInternalSalesBPCode(allocateApplyOrderUpdateDTO.getSapInternalSalesBPCode());
        //总部渠道编码
        allocateApplyOrderCreateDTO.setHeadquartersChannelCode(allocateApplyOrderUpdateDTO.getHeadquartersChannelCode());
        //总部组织编码 默认6000
        allocateApplyOrderCreateDTO.setHeadquartersOrganizationCode(allocateApplyOrderUpdateDTO.getHeadquartersOrganizationCode());

        //获取收货仓档案信息
        if (Objects.nonNull(allocateApplyOrderUpdateDTO.getReceiveWarehouseId())) {
            WmsSDO shipWmsSDO = InfoUtil.getWmsSDO(allocateApplyOrderUpdateDTO.getReceiveWarehouseId().toString());
            if (Objects.nonNull(shipWmsSDO) && Objects.nonNull(shipWmsSDO.getWarehouseId())) {
                allocateApplyOrderCreateDTO.setReceiveCargoZoneId(Integer.valueOf(shipWmsSDO.getWarehouseId()));
            }
        }
        //获取发货仓档案信息
        if (Objects.nonNull(allocateApplyOrderUpdateDTO.getShipWarehouseId())) {
            WmsSDO shipWmsSDO = InfoUtil.getWmsSDO(allocateApplyOrderUpdateDTO.getShipWarehouseId());
            if (Objects.nonNull(shipWmsSDO) && Objects.nonNull(shipWmsSDO.getWarehouseId())) {
                allocateApplyOrderCreateDTO.setShipCargoZoneId(shipWmsSDO.getWarehouseId());
            }
        }
        //地址信息
        if (Objects.nonNull(allocateApplyOrderCreateDTO.getCustomerAddress())) {
            log.info("创建调拨预报单查询客户地址入参code：" + allocateApplyOrderCreateDTO.getCustomerAddress());
            BatchQueryByIdsRequest batchQueryByIdsRequest = new BatchQueryByIdsRequest();
            batchQueryByIdsRequest.setIdList(Lists.newArrayList(allocateApplyOrderCreateDTO.getCustomerAddress()));
            log.info("AllocateApplyOrderWriteServiceImpl.sapCreateAllocateApplyOrder.batchQueryByIds,request:{}", JSON.toJSONString(batchQueryByIdsRequest));
            Result<List<CustomerAddress>> listResult = customerAddressService.batchQueryByIds(batchQueryByIdsRequest);
            log.info("AllocateApplyOrderWriteServiceImpl.sapCreateAllocateApplyOrder.batchQueryByIds,result:{}", JSON.toJSONString(listResult));
            allocateApplyOrderCreateDTO.setCustomerAddressId(allocateApplyOrderCreateDTO.getCustomerAddress());
            if (Objects.nonNull(listResult) && CollectionUtils.isNotEmpty(listResult.getResult())) {
                List<CustomerAddress> addressList = listResult.getResult();
                for (CustomerAddress customerAddress : addressList) {
                    allocateApplyOrderCreateDTO.setCustomer(customerAddress.getCustomerCode());
                    allocateApplyOrderCreateDTO.setCustomerAddress(customerAddress.getAddressCode());
                }
            }
        }

        //插入调拨预报单
        AllocateApplyOrderEntity allocateApplyOrderEntity = AllocateApplyOrderFactory.create(allocateApplyOrderCreateDTO);
        String code = allocateApplyOrderEntity.create();
        //查询预调拨单
        log.info("AllocateApplyOrderWriteServiceImpl.sapCreateAllocateApplyOrder.queryAllocateApplyOrderByCode,allocateApplyOrderResponseRequest:{}", JSON.toJSONString(code));
        AllocateApplyOrderResponse allocateApplyOrderResponse = allocateApplyOrderReadRepository.queryAllocateApplyOrderByCode(code);
        log.info("AllocateApplyOrderWriteServiceImpl.sapCreateAllocateApplyOrder.queryAllocateApplyOrderByCode,allocateApplyOrderResponseResult:{}", JSON.toJSONString(allocateApplyOrderResponse));
        if (Objects.isNull(allocateApplyOrderResponse) || Objects.isNull(allocateApplyOrderResponse.getAllocateApplyOrderDetailDTO())) {
            return Result.success(NULL_STRING);
        }
        //标记sap待回复
        allocateApplyOrderUpdateDTO.setSapEndProcessing(1);
        allocateApplyOrderUpdateDTO.setStatus(AllocateApplyOrderStatusEnum.WAIT_ANSWER.getCode());
        allocateApplyOrderUpdateDTO.setId(allocateApplyOrderResponse.getAllocateApplyOrderDetailDTO().getId());

        //查找货品信息
        Set<String> codes = allocateApplyOrderUpdateDTO.getList().stream().map(AllocateApplyOrderDetailCreateDTO::getScItemId).collect(Collectors.toSet());
        QueryGoodsListUnifiedInventoryRequest allocateApplyOrderQueryGoodsListRequest = new QueryGoodsListUnifiedInventoryRequest();
        allocateApplyOrderQueryGoodsListRequest.setGoodsCodes(new ArrayList(codes));
        log.info("AllocateApplyOrderWriteServiceImpl.sapCreateAllocateApplyOrder.queryGoodsListUnifiedInventory,request:{}", JSON.toJSONString(allocateApplyOrderQueryGoodsListRequest));
        QueryGoodsListUnifiedInventoryResponse queryGoodsListResponse = platformEnhanceService.queryGoodsListUnifiedInventory(allocateApplyOrderQueryGoodsListRequest);
        log.info("AllocateApplyOrderWriteServiceImpl.sapCreateAllocateApplyOrder.queryGoodsListUnifiedInventory,queryGoodsListResponseRequest:{}", JSON.toJSONString(queryGoodsListResponse));
        List<AllocateApplyOrderQueryGoodsListResponse> scItemGoodsList = new ArrayList<>();
        if (Objects.nonNull(queryGoodsListResponse)) {
            List result = queryGoodsListResponse.getResult();
            if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(result)) {
                scItemGoodsList = JSONObject.parseArray(JSONObject.toJSONString(result), AllocateApplyOrderQueryGoodsListResponse.class);
            }
        }
        //将货品信息转换成map
        if (CollectionUtils.isNotEmpty(scItemGoodsList)) {
            Map<String, AllocateApplyOrderQueryGoodsListDateilResponse> map = new HashMap<>();
            for (AllocateApplyOrderQueryGoodsListResponse allocateApplyOrderQueryGoodsListResponse : scItemGoodsList) {
                for (AllocateApplyOrderQueryGoodsListDateilResponse allocateApplyOrderQueryGoodsListDateilResponse : allocateApplyOrderQueryGoodsListResponse.getGoodsList()) {
                    map.put(allocateApplyOrderQueryGoodsListDateilResponse.getGoodsCode(), allocateApplyOrderQueryGoodsListDateilResponse);
                }
            }
            for (AllocateApplyOrderDetailCreateDTO allocateApplyOrderDetailCreateDTO : allocateApplyOrderUpdateDTO.getList()) {
                AllocateApplyOrderQueryGoodsListDateilResponse allocateApplyOrderQueryGoodsListDateilResponse = map.get(allocateApplyOrderDetailCreateDTO.getScItemId());
                allocateApplyOrderDetailCreateDTO.setScItemId(allocateApplyOrderQueryGoodsListDateilResponse.getGoodsCode());
                allocateApplyOrderDetailCreateDTO.setTitle(allocateApplyOrderQueryGoodsListDateilResponse.getGoodsName());
                allocateApplyOrderDetailCreateDTO.setStatus(AllocateApplyOrderStatusEnum.WAIT_ANSWER.getCode());
            }
        }
        allocateApplyOrderEntity = AllocateApplyOrderFactory.sapUpdate(allocateApplyOrderUpdateDTO);
        allocateApplyOrderEntity.sapCreate();
        //查询调拨预报单
        QueryAllocateApplyOrderRequest queryAllocateApplyOrderRequest = new QueryAllocateApplyOrderRequest();
        queryAllocateApplyOrderRequest.setCode(code);
        log.info("AllocateApplyOrderWriteServiceImpl.sapCreateAllocateApplyOrder.queryAllocateApplyOrderByCode,allocateApplyOrderDetailDTOResultRequest:{}", JSON.toJSONString(queryAllocateApplyOrderRequest));
        Result<AllocateApplyOrderDetailDTO> allocateApplyOrderDetailDTOResult = allocateApplyOrderReadService.queryAllocateApplyOrderByCode(queryAllocateApplyOrderRequest);
        log.info("AllocateApplyOrderWriteServiceImpl.sapCreateAllocateApplyOrder.queryAllocateApplyOrderByCode,allocateApplyOrderDetailDTOResultResult:{}", JSON.toJSONString(allocateApplyOrderDetailDTOResult));
        //添加单据日志
        Map<String, String> features = new HashMap<>();
        features.put(CODE, queryAllocateApplyOrderRequest.getCode());
        features.put(STATUS, allocateApplyOrderDetailDTOResult.getResult().getStatus().toString());
        saveDocumentLog(new AllocateApplyOrderDetailDTO(), allocateApplyOrderDetailDTOResult.getResult(), Integer.valueOf(AllocateApplyOrderOperationTypeEnum.CREATE.getValue()), features);
        log.info("AllocateApplyOrderWriteServiceImpl.sapCreateAllocateApplyOrder,result:{}", JSON.toJSONString(Result.success(code)));
        return Result.success(code);
    }

    /**
     * 批量提交调拨预报单
     * @param allocateApplyOrderBatchSubmitRequest
     * @return
     */
    @Override
    @FacadeInvoker(errorCode = "OTS-03-005-00-15-093")
    public Result<List<AllocateApplyOrderBatchSubmitResponse>> batchSubmit(AllocateApplyOrderBatchSubmitRequest allocateApplyOrderBatchSubmitRequest) {
        log.info("AllocateApplyOrderWriteServiceImpl.batchSubmit:{}", JSON.toJSONString(allocateApplyOrderBatchSubmitRequest));
        if (allocateApplyOrderBatchSubmitRequest == null || CollectionUtils.isEmpty(allocateApplyOrderBatchSubmitRequest.getIdList())){
            throw new FacadeException("OTS-03-005-00-15-092");
        }
        List<String> idList = allocateApplyOrderBatchSubmitRequest.getIdList().stream()
                .distinct().collect(Collectors.toList());
        QueryListByIdsRequest queryListByIdsRequest = new QueryListByIdsRequest();
        queryListByIdsRequest.setIds(idList);
        //查询出要批量提交的预报单
        Result<List<AllocateApplyOrder>> listResult = allocateApplyOrderService.queryListByIds(queryListByIdsRequest);
        List<AllocateApplyOrderBatchSubmitResponse> responses = Lists.newArrayList();
        if (listResult == null || CollectionUtils.isEmpty(listResult.getResult())){
            return Result.success(responses);
        }
//        allocateApplyOrderDetailService.
        //循环提交
        for (AllocateApplyOrder allocateApplyOrder : listResult.getResult()) {
            //如果是草稿状态
            if (!AllocateApplyOrderStatusEnum.DRAFT.getCode().equals(allocateApplyOrder.getStatus())){
                continue;
            }
            if (StringUtils.isBlank(allocateApplyOrder.getCode())){
                log.info("AllocateApplyOrderWriteServiceImpl.batchSubmit.codeIsNull:{}",JSON.toJSONString(allocateApplyOrder));
                continue;
            }
            QueryAllocateApplyOrderRequest queryAllocateApplyOrderRequest = new QueryAllocateApplyOrderRequest();
            queryAllocateApplyOrderRequest.setCode(allocateApplyOrder.getCode());
            //查询详情 数据直接用于提交
            Result<AllocateApplyOrderDetailDTO> allocateApplyOrderDetailDTOResult = allocateApplyOrderReadService.queryAllocateApplyOrderByCode(queryAllocateApplyOrderRequest);
            AllocateApplyOrderDetailDTO allocateApplyOrderDetailDTO = allocateApplyOrderDetailDTOResult.getResult();
            AllocateApplyOrderUpdateDTO allocateApplyOrderUpdateDTO = JSON.parseObject(JSON.toJSONString(allocateApplyOrderDetailDTO),
                    AllocateApplyOrderUpdateDTO.class);
            AllocateApplyOrderBatchSubmitResponse response = new AllocateApplyOrderBatchSubmitResponse();
            try{
                Result<Boolean> booleanResult = submitAllocateApplyOrder(allocateApplyOrderUpdateDTO);
                if (booleanResult != null && !Boolean.TRUE.equals(booleanResult.getResult())){
                    response.setCode(allocateApplyOrder.getCode());
                    response.setReason("提交结果失败");
                    responses.add(response);
                }
            }catch (Throwable e){
                response.setCode(allocateApplyOrder.getCode());
                response.setReason(e.getMessage());
                responses.add(response);
                log.error("AllocateApplyOrderWriteServiceImpl.batchSubmit.submitAllocateApplyOrder.error", e);
            }
        }
        if (CollectionUtils.isEmpty(responses)){
            return Result.success(responses);
        }
        log.info("AllocateApplyOrderWriteServiceImpl.batchSubmit.errorResult:{}",JSON.toJSONString(responses));
//        return Result.fail(responses,"OTS-03-005-00-15-094","调拨单预报单批量提交有失败的");
        return Result.success(responses);
    }

    void convert(AllocateApplyOrderDetailDTO detailDTO,AllocateApplyOrderUpdateDTO updateDTO){
//        updateDTO.setId(detailDTO.getId());
//        updateDTO.setCode(detailDTO.getCode());
//        updateDTO.setOutAllocateApplyOrderId(detailDTO.getOutAllocateApplyOrderId());
//        updateDTO.setBorrowGoodsTransfer0rderCode(detailDTO.getBorrowGoodsTransfer0rderCode());
//        updateDTO.setType(detailDTO.getType());
    }

    public Result<List<DeliveryWarehouseChoiceDTO>> queryDeliveryWarehouseByType(QueryDeliveryWarehouseByTypeRequest queryDeliveryWarehouseByTypeRequest,
                                                                                 Result<List<com.epoch.app.otsplatformenhance.sdo.OrganizationSDO>> loginEmployeeSaleOrganization) {
        /**
         * 	发货仓库：
         * 	单据类型1:默认为第一个可选择的工厂类型的仓库；
         * 	单据类型2:可选仓库类型为工厂、共享仓；默认选择第一个；
         * 	单据类型3、4:仅可选择共享仓，默认选择第一个；
         */
        List<DeliveryWarehouseChoiceDTO> deliveryWarehouseChoiceDTOS = new ArrayList<>();
        SearchCargoZoneListRequest searchCargoZoneListRequest = new SearchCargoZoneListRequest();
        //1启用状态
        searchCargoZoneListRequest.setStatus(1);
        //1是仓库档案，3是逻辑仓
        searchCargoZoneListRequest.setModel(3);
        searchCargoZoneListRequest.setName(queryDeliveryWarehouseByTypeRequest.getName());
        if (org.apache.commons.lang.StringUtils.isNotEmpty(queryDeliveryWarehouseByTypeRequest.getCode())){
            searchCargoZoneListRequest.setCode(queryDeliveryWarehouseByTypeRequest.getCode());
        }
        String type = queryDeliveryWarehouseByTypeRequest.getType();
        searchCargoZoneListRequest.setSize(99);
//        Result<List<com.epoch.app.otsplatformenhance.sdo.OrganizationSDO>> loginEmployeeSaleOrganization = otsPlatformEnhanceService.getLoginEmployeeSaleOrganization();
        List<String> codeList = null;
        if (Objects.nonNull(loginEmployeeSaleOrganization)&&Objects.nonNull(loginEmployeeSaleOrganization.getResult())) {
            Set<String> codes = loginEmployeeSaleOrganization.getResult().stream().map(com.epoch.app.otsplatformenhance.sdo.OrganizationSDO::getId).collect(Collectors.toSet());
            if (org.apache.dubbo.common.utils.CollectionUtils.isNotEmpty(codes)) {
                codeList = new ArrayList(codes);
            }
        }
        GetLoginEmployeeInfoResponse loginEmployeeInfo = baseDataService.getLoginEmployeeInfo();
        if (loginEmployeeInfo != null && loginEmployeeInfo.getOrganizationSDO()!= null){
            boolean isSalesMan = false;
            com.epoch.app.bcots.model.dto.OrganizationSDO organizationSDO = loginEmployeeInfo.getOrganizationSDO();
            if (org.apache.dubbo.common.utils.CollectionUtils.isNotEmpty(loginEmployeeInfo.getRoles())){
                for (RoleSDO role : loginEmployeeInfo.getRoles()) {
                    if (SALES_MAN_ROLE_CODE.equals(role.getCode())){
                        isSalesMan = true;
                    }
                }
                //如果是业务员的 需要找到业务员的销售组织这一层 而非分子公司
                if (isSalesMan){
                    while (!Objects.equals(104,organizationSDO.getType())){
                        BaselineGetOrganizationById2Request baselineGetOrganizationById2Request =
                                new BaselineGetOrganizationById2Request();
                        if (org.apache.commons.lang.StringUtils.isBlank(organizationSDO.getParentId())){
                            log.info("ForecastWarehouseSerivceImpl.queryDeliveryWarehouseByType.salesMan.org.errResult:{}",JSON.toJSONString(organizationSDO));
                            break;
                        }
                        baselineGetOrganizationById2Request.setId(organizationSDO.getParentId());
                        Result<com.epoch.app.bcots.model.dto.OrganizationSDO> organizationSDOResult = baseDataService.baselineGetOrganizationById2(baselineGetOrganizationById2Request);
                        if (organizationSDOResult == null || organizationSDOResult.getResult() == null){
                            log.info("ForecastWarehouseSerivceImpl.queryDeliveryWarehouseByType.salesMan.org.errResult:{}",JSON.toJSONString(organizationSDOResult));
                            break;
                        }
                        organizationSDO = organizationSDOResult.getResult();
                        if (organizationSDO.getType() != null && organizationSDO.getType() < 104){
                            log.info("ForecastWarehouseSerivceImpl.queryDeliveryWarehouseByType.salesMan.org.errResult:{}",JSON.toJSONString(organizationSDOResult));
                            break;
                        }
                        //如果是分子公司 就把值给填进去 查到销售组织这一层级就可以
                        if (Objects.equals(104,organizationSDO.getType())){
                            if (codeList == null){
                                codeList = Lists.newArrayList();
                            }else {
                                codeList.clear();
                            }
                            codeList.add(organizationSDO.getId());
                        }

                    }
                }
            }
        }
        if (Objects.isNull(type)){
            List<Integer> types = new ArrayList<>();
            types.add(2);
            types.add(5);
            searchCargoZoneListRequest.setTypeList(types);
            deliveryWarehouseChoiceDTOS.addAll(searchCargoZoneList(searchCargoZoneListRequest));
        }else{
            //计划调拨 查工厂 不做组织过滤
            if ("1".equals(type)) {
                searchCargoZoneListRequest.setTypeList(Lists.newArrayList(5));
                deliveryWarehouseChoiceDTOS.addAll(searchCargoZoneList(searchCargoZoneListRequest));
            }

            //销售组织 工厂数据返回
            if ("2".equals(type)) {
                //同是总部销售调拨单, 如果是工厂直发的 F-b那就只查出工厂
                //2共享仓  3销售单元仓 5工厂仓
                if(Objects.equals(Boolean.TRUE,queryDeliveryWarehouseByTypeRequest.getIsDTC())){
                    //如果是工厂直发的 现在放出F1共享仓 即新增F1-b
                    List<Integer> types = new ArrayList<>();
                    types.add(5);
                    searchCargoZoneListRequest.setTypeList(Lists.newArrayList(types));
                    deliveryWarehouseChoiceDTOS.addAll(searchCargoZoneList(searchCargoZoneListRequest));

                    //共享仓 权限过滤
                    types = new ArrayList<>();
                    types.add(2);
                    searchCargoZoneListRequest.setTypeList(types);
                    searchCargoZoneListRequest.setSaleOrgIdList(codeList);
                    deliveryWarehouseChoiceDTOS.addAll(searchCargoZoneList(searchCargoZoneListRequest));

                }else {
                    //如果是非工厂直发的总部销售  F-B F1-B
                    //工厂仓 不做权限过滤
                    List<Integer> types = new ArrayList<>();
                    types.add(5);
                    searchCargoZoneListRequest.setTypeList(Lists.newArrayList(types));
                    deliveryWarehouseChoiceDTOS.addAll(searchCargoZoneList(searchCargoZoneListRequest));
                    //共享仓 权限过滤
                    types = new ArrayList<>();
                    types.add(2);
                    searchCargoZoneListRequest.setTypeList(Lists.newArrayList(types));
                    searchCargoZoneListRequest.setSaleOrgIdList(codeList);
                    deliveryWarehouseChoiceDTOS.addAll(searchCargoZoneList(searchCargoZoneListRequest));
                }
            }


//            //销售组织 工厂数据返回
//            if ("2".equals(type)) {
//
//                List<Integer> types = new ArrayList<>();
//                types.add(2);
//                types.add(5);
//                searchCargoZoneListRequest.setTypeList(Lists.newArrayList(types));
//                deliveryWarehouseChoiceDTOS.addAll(searchCargoZoneList(searchCargoZoneListRequest));
////                List<Integer> types = new ArrayList<>();
////                types.add(2);
////                searchCargoZoneListRequest.setTypeList(types);
////                searchCargoZoneListRequest.setSaleOrgIdList(codeList);
////                deliveryWarehouseChoiceDTOS.addAll(searchCargoZoneList(searchCargoZoneListRequest));
//            }
            //同公司调拨 共享仓 组织过滤
            if ("3".equals(type)) {
                List<Integer> types = new ArrayList<>();
                types.add(2);
                searchCargoZoneListRequest.setTypeList(types);
                searchCargoZoneListRequest.setSaleOrgIdList(codeList);
                deliveryWarehouseChoiceDTOS.addAll(searchCargoZoneList(searchCargoZoneListRequest));
            }
            //查全部
            if ("4".equals(type)) {
                searchCargoZoneListRequest.setTypeList(Lists.newArrayList(2));
                deliveryWarehouseChoiceDTOS.addAll(searchCargoZoneList(searchCargoZoneListRequest));
            }
        }

        return Result.success(deliveryWarehouseChoiceDTOS);
    }


    public Result<List<DeliveryWarehouseChoiceDTO>> queryReceivingWarehouseByType(QueryReceivingWarehouseByTypeRequest queryReceivingWarehouseByTypeRequest,
                                                                                  Result<List<com.epoch.app.otsplatformenhance.sdo.OrganizationSDO>> loginEmployeeSaleOrganization ) {
        /**
         * 	收货仓库：选择提报组织下的逻辑仓库；
         * 	取值范围：通过所选的提报组织，查询对应的逻辑库（货区）
         * 	展示方式：仓库名称 / 货区名称
         * 	选择范围
         * 	单据类型1、3、4，仅可选择共享仓；
         * 	单据类型2、仅可选择销售单元仓；
         */
        List<DeliveryWarehouseChoiceDTO> deliveryWarehouseChoiceDTOS = new ArrayList<>();
        SearchCargoZoneListRequest searchCargoZoneListRequest = new SearchCargoZoneListRequest();
        //1启用状态
        searchCargoZoneListRequest.setStatus(1);
        //1是仓库档案，3是逻辑仓
        searchCargoZoneListRequest.setModel(3);
        searchCargoZoneListRequest.setName(queryReceivingWarehouseByTypeRequest.getName());

        if (org.apache.commons.lang.StringUtils.isNotEmpty(queryReceivingWarehouseByTypeRequest.getCode())){
            searchCargoZoneListRequest.setCode(queryReceivingWarehouseByTypeRequest.getCode());
        }
        searchCargoZoneListRequest.setSize(99);
        //查找销售组织
        String type = queryReceivingWarehouseByTypeRequest.getType();
//        Result<List<com.epoch.app.otsplatformenhance.sdo.OrganizationSDO>> loginEmployeeSaleOrganization = otsPlatformEnhanceService.getLoginEmployeeSaleOrganization();
        if (Objects.nonNull(loginEmployeeSaleOrganization)&&Objects.nonNull(loginEmployeeSaleOrganization.getResult())){
            Set<String> codes = loginEmployeeSaleOrganization.getResult().stream().map(com.epoch.app.otsplatformenhance.sdo.OrganizationSDO::getId).collect(Collectors.toSet());
            if (org.apache.dubbo.common.utils.CollectionUtils.isNotEmpty(codes)){
                searchCargoZoneListRequest.setSaleOrgIdList(new ArrayList(codes));
                if (Objects.isNull(type)){
                    List<Integer> types = new ArrayList<>();
                    types.add(2);
                    types.add(3);
                    searchCargoZoneListRequest.setTypeList(types);
                    deliveryWarehouseChoiceDTOS.addAll(searchCargoZoneList(searchCargoZoneListRequest));
                }else{
                    if ("1".equals(type)||"3".equals(type)||"4".equals(type)){
                        //查询共享仓
                        searchCargoZoneListRequest.setTypeList(Lists.newArrayList(2));
                        deliveryWarehouseChoiceDTOS.addAll(searchCargoZoneList(searchCargoZoneListRequest));
                    }
                    if ("2".equals(type)){
                        //销售单元仓
                        searchCargoZoneListRequest.setTypeList(Lists.newArrayList(3));
                        deliveryWarehouseChoiceDTOS.addAll(searchCargoZoneList(searchCargoZoneListRequest));
                    }
                }
            }
        }
        return Result.success(deliveryWarehouseChoiceDTOS);
    }

    private List<DeliveryWarehouseChoiceDTO> searchCargoZoneList(SearchCargoZoneListRequest searchCargoZoneListRequest) {
        SearchCargoZoneListResponse searchCargoZoneListResponse = unifiedInventoryService.searchCargoZoneList(searchCargoZoneListRequest);
        List<WarehouseInfo> result = searchCargoZoneListResponse.getResult();
        List<DeliveryWarehouseChoiceDTO> deliveryWarehouseChoiceDTOS = new ArrayList<>();
        if (org.apache.dubbo.common.utils.CollectionUtils.isNotEmpty(result)){
            for (WarehouseInfo warehouseInfo : result) {
                DeliveryWarehouseChoiceDTO dto = new DeliveryWarehouseChoiceDTO();
                dto.setValue(warehouseInfo.getId());
                dto.setLabel(warehouseInfo.getName());
                dto.setSapDeliveryBPCode(warehouseInfo.getSapDeliveryBPCode());
                dto.setSapSaleBPCode(warehouseInfo.getSapSaleBPCode());
                dto.setSapInternalSalesBPCode(warehouseInfo.getSapInternalSalesBPCode());
                dto.setSapInternalDeliveryBPCode(warehouseInfo.getSapInternalDeliveryBPCode());
                deliveryWarehouseChoiceDTOS.add(dto);
            }
        }
        return deliveryWarehouseChoiceDTOS;

    }
}
